[英]Id with RadioButtonFor
I'm trying to deal with radiobutton ids in asp MVC 5 我正在尝试处理ASP MVC 5中的单选按钮ID
I'm working like this 我这样工作
Example model 示例模型
class A
{
public bool? radio { get; set; }
}
and in razor view 并在剃刀视图中
@Html.RadioButtonFor(x => x.NeutroBT, Model.NeutroBT, new { @id = "True"})
@Html.RadioButtonFor(x => x.NeutroBT, !Model.NeutroBT, new { @id = "False})
It doesn't cause problem, but I'm working in an editortemplate, and I want it to have generated id
, to access in some way like @Html.IdFor(x => x.NeutroBT, true)
and @Html.IdFor(x => x.NeutroBT, false)
from the other views, just preventing changes in the future 它不会引起问题,但是我正在使用一个编辑器模板,并且我希望它生成
id
,以某种方式进行访问,例如@Html.IdFor(x => x.NeutroBT, true)
和@Html.IdFor(x => x.NeutroBT, false)
从其他观点来看,只是防止将来发生变化
Is some like this possible? 有可能这样吗? I pass a lot of time searching and I didn't get anything similar
我花了很多时间进行搜索,但没有得到任何类似的结果
If is not possible, what is the best way to deal with it? 如果不可能,最好的处理方法是什么?
thanks! 谢谢!
There is no need to use an id
attribute. 无需使用
id
属性。 Instead you can just use the name
attribute to select or set the value via javascript (and in any case, @Html.IdFor() will only ever return
NeutroBT , not the
id that you override in the
RadioButtonFor()` method so it cannot be used in your case) 相反,您可以只使用
name
属性来通过javascript选择或设置值(无论如何, @Html.IdFor() will only ever return
NeutroBT , not the
that you override in the
RadioButtonFor()方法中that you override in the
, not the
id that you override in the
因此它不能用于您的情况)
In addition, the 2nd parameter of RadioButtonFor()
should be true
or false
(not Model.NeutroBT
and !Model.NeutroBT
). 另外,
RadioButtonFor()
的第二个参数应该为true
或false
(不是Model.NeutroBT
和!Model.NeutroBT
)。
And to associate a label with the button, you can wrap it in a <label>
, for example 要将标签与按钮相关联,可以将其包装在
<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>
Note that new { id = "" }
removes the id
attribute and prevents invalid html due to duplicate id
attributes. 请注意,
new { id = "" }
会删除id
属性,并防止由于id
属性重复而导致无效的html。
Then to access the selected value using jQuery 然后使用jQuery访问选定的值
var selectedValue = $('input[name="' + @Html.NameFor(x => x.NeutroBT) + '"]:checked').val();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.