Set a RadioButtonFor() checked by default within a Foreach loop(在 Foreach 循环中设置默认选中的 RadioButtonFor())
问题描述
我使用 @Html.RadioButtonFor
扩展方法有一个奇怪的行为.我正在使用 foreach 循环来创建 RadioButton 和 By 三元运算符的列表.我正在尝试将尊重条件的人设置为检查,但始终是最后一个被检查的人.我搜索了类似的问题,但我不确定是否找到了一些东西.而且我不想创建/使用自定义 RadioButtonList
.
这是我的视图中的代码:
@foreach(Model.Entities 中的变量项){@Html.RadioButtonFor(m => item.Default, item.EntityId,新的 { @checked = item.Default ?"checked" : "" })//item.Default 是一个布尔值,只有一个设置为 True</div>}但在我的浏览器中,即使 item.Default
为 false
,它始终是最后创建的 checked
.那么有什么事情吗
解决方案 如果存在 checked
属性(无论它的实际值是什么),浏览器都会将按钮视为已选中.这是 HTML5 行为.我猜所有单选按钮都定义了 checked
属性,浏览器将选择最后一个按钮作为最终选择的按钮.
我的解决方案是创建一个自定义 RadioButtonFor 扩展方法,该方法接受一个布尔值作为选中状态,并根据值将选中属性添加到 htmlAttributes 字典.像这样:
public static MvcHtmlString RadioButtonFor(this HtmlHelper htmlHelper, Expression> 表达式, 对象值, 对象htmlAttributes, bool checkedState){var htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);如果(检查状态){htmlAttributeDictionary.Add("checked", "checked");}返回 htmlHelper.RadioButtonFor(表达式, 值, htmlAttributeDictionary);}
然后您可以在视图中使用该方法(不要忘记添加您创建扩展方法的名称空间并将其放入配置中),如下所示:
@foreach(Model.Entities 中的变量项){@Html.RadioButtonFor(m => item.Default, item.EntityId, new {/* 其他属性放在这里 *