views:

49

answers:

2

Okay, pretty simple question. I think I need to drop in some escape characters, but I'm not quite sure where.

Here is the javascript function I'm attempting to call:

function setData(associateValue, reviewDateValue) {
    var associate = document.getElementById("Associate");
    var reviewDate = document.getElementById("ReviewDate");
    associate.value = associateValue;
    reviewDate.value = reviewDateValue;
}

Here is the asp .net mvc line where I'm attempting to create a Radio button with a click event that calls the above function and passes data from the model as javascript parameter values.

<%= Html.RadioButton("Selected", item.Selected, new { onClick="setData('<%=item.Associate%>','<%=item.ReviewDate%>' )"  } )%>

The above throws a bunch of compile issues and doesn't work. A call such as the following does call the javascript, but doesn't get the data from the model.

<%= Html.RadioButton("Selected", item.Selected, new { onClick="setData('item.Associate','item.ReviewDate' )"  } )%>

<%= Html.RadioButton("Selected", item.Selected, new { onClick="setData('item.Associate','item.ReviewDate' )"  } )%>

Thoughts?

SOLUTION

        <% String functionCall = String.Format("setData('{0}','{1}')", Html.Encode(item.Associate), Html.Encode(item.ReviewDate )) ;  %>
        <%= Html.RadioButton("Selected", item.Selected, new { onClick=functionCall  } )%>                
+1  A: 

It should be like this:

<%: Html.RadioButton("Selected", item.Selected, new { onClick="setData('" + Html.Encode(item.Associate) + "','" + Html.Encode(item.ReviewDate) + "' )"  } )%>

And if it's MVC2 you should prefer to use : instead of = to make sure it's HTML-encoded.

Peter Forss
Note that `<%:` doesn't actually make any difference here, since Html.RadioButton returns an IHtmlString which won't be touched by `<%:`. However, it's good advice to get into the habit of using `<%:` by default, only using `<%=` when you know you need it.
stevemegson
+4  A: 

You need to properly build the string that represents the onclick evenet handler:

onClick = String.Format("setData('{0}', '{1}')", item.Association, item.ReviewData)
marcind
+1, simply add a HTML encode to ensure possible quotes in model data are properly escaped.
Darin Dimitrov
Love this answer marc. Very simple.
Jason