带有 RadioButtonFor 的 Id
Id with RadioButtonFor
我正在尝试处理 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)
从其他的观点来看,只是为了防止以后的变化
这样的可能吗?我花了很多时间搜索,但没有找到类似的东西
如果不可能,最好的处理方法是什么?
谢谢!
不需要使用 id
属性。相反,您可以将 name
属性用于 select 或通过 javascript 设置值(无论如何,@Html.IdFor() will only ever return
NeutroBT, not the
idthat you override in the
RadioButtonFor()` 方法,所以它不能用于你的情况)
此外,RadioButtonFor()
的第二个参数应该是true
或false
(不是Model.NeutroBT
和!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
访问 selected 值
var selectedValue = $('input[name="' + @Html.NameFor(x => x.NeutroBT) + '"]:checked').val();
我正在尝试处理 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)
从其他的观点来看,只是为了防止以后的变化
这样的可能吗?我花了很多时间搜索,但没有找到类似的东西
如果不可能,最好的处理方法是什么?
谢谢!
不需要使用 id
属性。相反,您可以将 name
属性用于 select 或通过 javascript 设置值(无论如何,@Html.IdFor() will only ever return
NeutroBT, not the
idthat you override in the
RadioButtonFor()` 方法,所以它不能用于你的情况)
此外,RadioButtonFor()
的第二个参数应该是true
或false
(不是Model.NeutroBT
和!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
访问 selected 值var selectedValue = $('input[name="' + @Html.NameFor(x => x.NeutroBT) + '"]:checked').val();