0

I have some jQuery I'm using to "do stuff" depending on the value of a selected radio button. It works perfectly fine and as expected...until I submit the page and POST back to itself. After a POST, the value of 'this' within the function is always the first radio button - "filterByCategory1". I think this has something to do with MVCs abusing of radio button id's (same id for multiple buttons), but that's an uneducated guess.

the jQuery:

$('input[id^="filterBy"]').change(function (e) {
    if ($(this).val() == 'filterByCategory1') {
        // do stuff
    } else if ($(this).val() == 'filterByCategory2') {
        // do other stuff
    }
});

// Just to make "do stuff" happen on initial page load
$('#filterBy').change();

The razor bit

@Html.RadioButtonFor(x => x.filterBy, "filterByCategory1", new { @checked = "checked" }) One <br />
@Html.RadioButtonFor(x => x.filterBy, "filterByCategory2") Two
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
keyvaluepear
  • 29
  • 1
  • 8

2 Answers2

1

Indeed, the same id is used for both radios which results into an invalid markup. I would recommend you using class names:

@Html.RadioButtonFor(
    x => x.filterBy, 
    "filterByCategory1", 
    new { id = "filterByCategory1", @class = "myradio" }
) 

@Html.RadioButtonFor(
    x => x.filterBy, 
    "filterByCategory2",
    new { id = "filterByCategory2", @class = "myradio" }
)

and then:

$('.myradio').change(function (e) {
    if ($(this).val() == 'filterByCategory1') {
        // do stuff
    } else if ($(this).val() == 'filterByCategory2') {
        // do other stuff
    }
});

notice that I have removed the checked attribute from the first radio as well as the explicit .change() call in your javascript. The correct way to select the checked radio button in ASP.NET MVC is to provide a value in the controller action that renders this view:

MyViewModel model = ...
model.filterBy = "filterByCategory1"; // set the first button as checked
return View(model);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for the bit about setting the selected value in the model - conceptually I wasn't thinking about that. This route worked easily, and then all I needed to do was attach a .each to 'myradio' as well to handle "doing stuff" on page loads (and not just clicks). Worked perfectly. Thank you! – keyvaluepear Jul 15 '11 at 18:49
0

If the radio buttons are not grouped by name the change event will not work and infact even the radio buttons will not work as expected. You should use Html.RadioButtonListFor in order to group them together so that when they are rendered they will have the same name attribute but different id. Take a look at the below link.

Has anyone implement RadioButtonListFor<T> for ASP.NET MVC?

Community
  • 1
  • 1
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124