gpt4 book ai didi

c# - 设置在 Foreach 循环中默认选中的 RadioButtonFor()

转载 作者:行者123 更新时间:2023-12-02 07:44:23 25 4
gpt4 key购买 nike

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

这是我的 View 中的代码:

@foreach (var item in Model.Entities)
{
<div>
@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
</div>
}

但在我的浏览器中,即使item.Defaultfalse,它始终是最后一个被检查创建的。那么有什么吗

最佳答案

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

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

    public static MvcHtmlString RadioButtonFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object value, object htmlAttributes, bool checkedState)
{
var htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

if (checkedState)
{
htmlAttributeDictionary.Add("checked", "checked");
}

return htmlHelper.RadioButtonFor(expression, value, htmlAttributeDictionary);
}

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

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

关于c# - 设置在 Foreach 循环中默认选中的 RadioButtonFor(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23382612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com