views:

906

answers:

3

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  A: 

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>
tvanfosson
what makes you think he is using vb, with the "new" keywoard, it looks like he is using c#.
J.W.
Because the error looks like a compiler error, not a browser error, and, if so, indicates that it is expecting class identifier or the With keyword for anonymous types. I wouldn't expect this to be the case if the page language is C#.
tvanfosson
expecting VB instead of C# is what popped into my head as well... This answer is likely spot on.
Funka
A: 

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.

J.W.
I replaced Yes() with alert and had the same problem
photo_tom
A: 

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

photo_tom