html.radiobuttonfor 默认选中,c# – 在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.Default为false,它也始终是最后创建的.

那有什么东西

解决方法:

如果存在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)

}

标签:c,radio-button,razor,asp-net-mvc-4

来源: https://codeday.me/bug/20190528/1174091.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值