在Foreach循环中默认选中设置RadioButtonFor()

我使用@Html.RadioButtonFor扩展方法有一个奇怪的行为。 我正在使用foreach循环来创建RadioButton和By三元运算符列表。 我试图设置一个尊重条件的人来检查,但它始终是最后一个被检查的人。 我搜索了类似的问题,但我不确定是否找到了什么。 而且我不想创建/使用自定义的RadioButtonList

在我的视图中我的代码:

 @foreach (var item in Model.Entities) { 
@Html.RadioButtonFor(m => item.Default, item.EntityId, new { @checked = item.Default ? "checked" : "" })//item.Default is a bool and there is only one set to True
}

但是在我的浏览器中,即使item.Defaultfalse它也始终是最后创建的。 那有什么东西

如果存在checked属性(无论它的实际值是什么),浏览器会将按钮视为已选中。 这是HTML5行为。 我猜所有的radiobuttons都定义了checked属性,浏览器会选择最后一个按钮作为最终选择的按钮。

我的解决方案是创建一个自定义的RadioButtonFor扩展方法,它接受一个检查状态的布尔值,并根据值将checked属性添加到htmlAttributes字典。 像这样的东西:

  public static MvcHtmlString RadioButtonFor(this HtmlHelper htmlHelper, Expression> expression, object value, object htmlAttributes, bool checkedState) { var htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); if (checkedState) { htmlAttributeDictionary.Add("checked", "checked"); } return htmlHelper.RadioButtonFor(expression, value, htmlAttributeDictionary); } 

然后,您可以在视图中使用该方法(不要忘记添加创建扩展方法的命名空间并将其放在配置中),如下所示:

  @foreach (var item in Model.Entities) { 
@Html.RadioButtonFor(m => item.Default, item.EntityId, new { /* other attributes go here */ }, item.Default)
}

运营商的优先权在这里引起了问题; 由于在比较之前存在平等,因此该短语将被评估为

 (@checked = item.Default) ? "checked" : "" 

而你想要它

 @checked = (item.Default ? "checked" : "")