问题
What I want to do is to call a JavaScript routine when the user clicks on a radiobutton. I've some fields to enable/disable when this happens. However, when I enter
 <%=Html.RadioButton("obp17", "57", ViewData.Eval("obpValue17").ToString().Equals("57"), new {@onclick = "Yes()"})%>
I'm getting a "type or with" expected error when trying to add the onlick event. This should be easy, but none of samples I've found seem to work. The leading "@" is common in all the examples I've found, but something else seems to be missing.
And yes I know the way of checking for "true" is overkill, but it is created with a special purpose code generator, so it wasn't any extra work.
Any thoughts?
回答1:
Do you have Yes() function correctly defined in your code ? Replace Yes() to the javascript alert() function ; if that works, then the line of code you posted is OK.
Also, please post Yes() function here, and I think there may be some error there.
回答2:
Pardon me for causing anyone problems. My problem was ultimately caused by delete the first line of the ASCX file that inherits "System.Web.Mvc.ViewUserControl" Once I put that in, all the problems went away.
The line of code that worked was
 <%= Html.TextBox("obpt9",ViewData.Eval("obpt9"), new { onclick = "alert('hi')" })%>
Different line than sample, but they are all the same.
Again, sorry for causing anyone confusion.
tom
回答3:
Is the page language VB or C#? If it's VB your syntax is wrong for creating the anonymous typed html attributes. See this MSDN reference on how to create an object with an anonymous type in VB.
 <%=Html.RadioButton("obp17",
                     "57",
                     ViewData.Eval("obpValue17").ToString().Equals("57"),
                     New With { .onclick = "Yes()" } ) %>
Or change the page language to C#, if that's more appropriate.
Also, note that you could (arguably should) simply give the radio button a class, then add all the handlers at one time with jQuery. Usually you want to keep your javascript separate from your mark up.
 <%=Html.RadioButton("obp17",
                     "57",
                     ViewData.Eval("obpValue17").ToString().Equals("57"),
                     New With { .class = "heinz" } ) %>
 <script type="text/javascript>
     $('.heinz').click( function() {
        ... implement the logic of Yes() here ...
     });
 </script>
回答4:
The general structure Looks like the following:
@Html.RadioButtonFor(t => t.ViewModelVariableName,"RadioButtonValue", new {javascriptEvent = "javascriptMethodName"});
来源:https://stackoverflow.com/questions/1224202/add-onclick-event-to-html-radiobutton