0

我正在尝试处理 asp MVC 5 中的单选按钮 ID

我正在这样工作

示例模型

class A
{
   public bool? radio { get; set; }
}

在剃刀视图中

@Html.RadioButtonFor(x => x.NeutroBT, Model.NeutroBT, new { @id = "True"})
@Html.RadioButtonFor(x => x.NeutroBT, !Model.NeutroBT, new { @id = "False})

它不会引起问题,但我正在编辑器模板中工作,我希望它已经生成id,以某种方式访问​​,就像@Html.IdFor(x => x.NeutroBT, true)@Html.IdFor(x => x.NeutroBT, false)其他视图一样,只是防止将来发生变化

有这样的可能吗?我花了很多时间搜索,但没有得到类似的东西

如果不可能,最好的处理方法是什么?

谢谢!

4

1 回答 1

2

不需要使用id属性。相反,您可以只使用该name属性通过 javascript 选择或设置值(在任何情况下,@Html.IdFor() will only ever returnNeutroBT , not theid that you override in theRadioButtonFor()` 方法因此不能在您的情况下使用)

另外,第二个参数RadioButtonFor()应该是trueor false(不是Model.NeutroBTand !Model.NeutroBT)。

并且要将标签与按钮相关联,您可以将其包装在 中<label>,例如

<label>
    @Html.RadioButtonFor(x => x.NeutroBT, true, new { id = ""})
    <span>Yes</span>
</label>
<label>
    @Html.RadioButtonFor(x => x.NeutroBT, false, new { id = ""})
    <span>No</span>
</label>

请注意,new { id = "" }删除id属性并防止由于重复id属性而导致的无效 html。

然后使用 jQuery 访问选定的值

var selectedValue = $('input[name="' + @Html.NameFor(x => x.NeutroBT) + '"]:checked').val();
于 2018-08-27T12:38:25.633 回答