简体   繁体   English

刷新ASP.Net MVC中的单选按钮问题

[英]Refresh Issue with Radio Buttons in ASP.Net MVC

I have a couple of radio buttons on screen in MVC. 我在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). 我选择了选项2,然后刷新页面(按F5键)。 I was expecting to see my Option 1 radion button to be selected as page refresh should revert to the initial stage. 我期望看到我的Option 1单选按钮被选中,因为页面刷新应该恢复到初始阶段。 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? 在MVC中有什么特别的事情需要重置单选按钮?

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 我什至尝试将这种逻辑放在$(document).ready中以便选择该选项,但它也没有使事情成真

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

Your jQuery has a bit of an issue. 您的jQuery有点问题。 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);

Solution : Using JavaScript(JQuery): 解决方案:使用JavaScript(JQuery):

@Html.RadioButton("rbChartType", "1", new { @id="rbChartType1" }) @Html.Label("Option1") @Html.RadioButton("rbChartType", "2", new { @id="rbChartType2" }) @Html.Label("Option2") @ Html.RadioButton(“ rbChartType”,“ 1”,新{@ id =“ rbChartType1”})@ Html.Label(“ Option1”)@ Html.RadioButton(“ rbChartType”,“ 2”,新{@ id = “ rbChartType2”})@ Html.Label(“ Option2”)

$(function () { var currentType = '@ViewBag.SelectedOption '; if (currentType == '1') { $("#rbChartType1").prop("checked", true); } if (currentType == '2') { $("#rbChartType2").prop("checked", true); } }); $(function(){var currentType ='@ViewBag.SelectedOption'; if(currentType =='1'){$(“#rbChartType1”)。prop(“ checked”,true);} if(currentType ==' 2'){$(“#rbChartType2”)。prop(“ checked”,true);}});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM