Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass model values as javascript function parameters from inside an asp.net mvc Html helper such a Html.Radio?

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  } )%>                
like image 757
jason Avatar asked Jul 20 '10 16:07

jason


2 Answers

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

onClick = String.Format("setData('{0}', '{1}')", item.Association, item.ReviewData)
like image 148
marcind Avatar answered Nov 14 '22 23:11

marcind


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.

like image 33
Peter Örneholm Avatar answered Nov 14 '22 23:11

Peter Örneholm