jQuery change function returning wrong value on POST w/ RadioButtonFor
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 开发者_JAVA百科/>
@Html.RadioButtonFor(x => x.filterBy, "filterByCategory2") Two
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);
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?
精彩评论