i.Value, "true")-6ren">
gpt4 book ai didi

asp.net-mvc-3 - 将 Html.RadioButtonFor 和 Html.LabelFor 用于相同的模型但不同的值

转载 作者:行者123 更新时间:2023-12-03 06:14:19 29 4
gpt4 key购买 nike

我有这个 Razor 模板

<table>
<tr>
<td>@Html.RadioButtonFor(i => i.Value, "1")</td>
<td>@Html.LabelFor(i => i.Value, "true")</td>
</tr>
<tr>
<td>@Html.RadioButtonFor(i => i.Value, "0")</td>
<td>@Html.LabelFor(i => i.Value, "false")</td>
</tr>
</table>

这给了我这个 HTML

<table>
<tr>
<td><input id="Items_1__Value" name="Items[1].Value" type="radio" value="1" /></td>
<td><label for="Items_1__Value">true</label></td>
</tr>
<tr>
<td><input checked="checked" id="Items_1__Value" name="Items[1].Value" type="radio" value="0" /></td>
<td><label for="Items_1__Value">false</label></td>
</tr>
</table>

所以我有两次 ID Items_1__Value ,这当然不好,并且在浏览器中不起作用,当我单击第二个标签“false”时,第一个 radio 将被激活。

我知道我可以在 RadioButtonFor 添加自己的 Id 并用我的标签引用它,但这不太好,不是吗?特别是因为我处于循环中,不能只使用名​​称“值”和添加的数字,这最终也会出现在我的最终 HTML 标记中的多个 Dom Id 中。

这不应该是一个好的解决方案吗?

最佳答案

不要为此过度设计解决方案。您想要完成的只是让单选按钮响应文本上的点击。保持简单,只需将单选按钮包裹在标签标签中即可:

<table>
<tr>
<td><label>@Html.RadioButtonFor(i => i.Value, "1")True</label></td>
</tr>
<tr>
<td><label>@Html.RadioButtonFor(i => i.Value, "0")False</label></td>
</tr>
</table>

LabelFor html 帮助程序通常用于从 View 模型上的 Display 属性引入名称(例如“[Display(Name = "Enter your Name")])。

对于单选按钮,该名称并不是特别有用,因为每个单选按钮都有不同的文本行,这意味着无论如何您都必须将文本硬编码到 View 中。

关于asp.net-mvc-3 - 将 Html.RadioButtonFor 和 Html.LabelFor 用于相同的模型但不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8320172/

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