开发者

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

开发者 https://www.devze.com 2023-01-07 22:05 出处:网络
Okay, pretty simple question. I think I need to drop in some escape characters, but I\'m not quite sure where.

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 fr开发者_StackOverflow中文版om 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  } )%>                


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

onClick = String.Format("setData('{0}', '{1}')", item.Association, item.ReviewData)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号