Reputation: 3410
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);
Upvotes: 1
Views: 1882
Reputation: 247
Solution : Using JavaScript(JQuery):
@Html.RadioButton("rbChartType", "1", new { @id="rbChartType1" }) @Html.Label("Option1") @Html.RadioButton("rbChartType", "2", new { @id="rbChartType2" }) @Html.Label("Option2")
$(function () { var currentType = '@ViewBag.SelectedOption '; if (currentType == '1') { $("#rbChartType1").prop("checked", true); } if (currentType == '2') { $("#rbChartType2").prop("checked", true); } });Upvotes: 0
Reputation: 5862
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);
Upvotes: 1