Add OnClick Event to Html.RadioButton

2019-08-15 16:53发布

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?

4条回答
萌系小妹纸
2楼-- · 2019-08-15 17:24

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

查看更多
倾城 Initia
3楼-- · 2019-08-15 17:24

The general structure Looks like the following:

@Html.RadioButtonFor(t => t.ViewModelVariableName,"RadioButtonValue", new {javascriptEvent = "javascriptMethodName"});
查看更多
叛逆
4楼-- · 2019-08-15 17:34

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>
查看更多
劫难
5楼-- · 2019-08-15 17:49

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.

查看更多
登录 后发表回答