通过检查checked单选按钮的属性行为 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio#checked,我发现你的问题出现是因为checked
attribute 是一个布尔属性,当该属性存在时,指示相应的输入元素处于选中状态,无论其值如何(checked="false"
与checked="true"
or checked="checked"
).
If checked
属性存在于同一组中的多个单选按钮,默认情况下它将最后一个单选按钮设置为checked
(see 这把小提琴 https://dotnetfiddle.net/4MTE7w基于您的原始代码)。因此,您需要排除checked
属性时CompanionReleaseRadio1.Checked
属性设置为 false 通过利用@functions
内联函数助手,如下例所示:
@functions {
private object SetRadioButtonChecked(bool isChecked, string RadioID)
{
// checked state from property
if (isChecked)
{
// checked attribute is present
return new { id = "CompanionReleaseRadio2" + RadioID, @checked = "checked" };
}
else
{
// checked attribute is not present
return new { id = "CompanionReleaseRadio2" + RadioID };
}
}
}
然后在里面调用上面的内联函数RadioButton
像这样的助手:
@foreach (var companionReleases1 in Model.CompanionReleaseRadios1)
{
<div class="col-sm-4">
@Html.RadioButtonFor(model => Model.CompanionReleaseRadio1, companionReleases1.RadioID,
@SetRadioButtonChecked(companionReleases1.Checked, companionReleases1.RadioID))
<span class="checkbox-label">@companionReleases1.RadioText</span>
</div>
}
之后,所有单选按钮都带有CompanionReleaseRadio1.Checked
属性设置为false
应该设置为未选中状态(参见这把小提琴 https://dotnetfiddle.net/7jDes8达到预期的结果)。
参考:
通过 Razor 语法在 ASP.NET 页面中使用 @functions https://blogs.msdn.microsoft.com/timlee/2010/07/30/using-functions-in-an-asp-net-page-with-razor-syntax/
相关问题:
如何在cshtml模板中创建函数? https://stackoverflow.com/questions/6531983/how-to-create-a-function-in-a-cshtml-template
asp.net mvc3 基于模型检查单选按钮 https://stackoverflow.com/questions/8111942/asp-net-mvc3-checking-radio-button-based-on-model