techspider techspider - 2 months ago 22
Javascript Question

Refresh Issue with Radio Buttons in ASP.Net MVC

I have a couple of radio buttons on screen in MVC. I set one of them as default selected on page load.

@Html.RadioButton("rbChartType", "1", isChecked: true) @Html.Label("Option1")
@Html.RadioButton("rbChartType", "2", isChecked: false) @Html.Label("Option2")

I selected Option 2, and refresh the page (presss F5). I was expecting to see my Option 1 radion button to be selected as page refresh should revert to the initial stage. But, I see my refresh action resets all other data on the page but not the radio button. Is there anything special need to be done in MVC to reset radio button back?

I even tried putting this logic in $(document).ready so as to select the option but it also didn't make things happen for me

$('input:radio[name=rbChartType]:nth(0)').attr('checked', true);


Your jQuery has a bit of an issue. It should either be:

 $('input:radio[name=rbChartType]:nth(0)').attr('checked', 'checked');

Or for newer versions:

 $('input:radio[name=rbChartType]:nth(0)').prop('checked', true);