MVC RadiobuttonFor剃刀如何使标签能点击? [英] MVC RadiobuttonFor Razor how to make label click able?
问题描述
我试图在剃刀语法单选按钮列表到目前为止,我想出这个
I'm trying to make a radiobuttonlist in razor syntax so far I have come up with this
@foreach (var p in Model)
{
<div id="projectList" class="col-lg-5">
@Html.RadioButton("name", "1", false, new { onCLick = "ShowOption(this)", id = p.id.ToString() })
@Html.Label(p.id.ToString(), p.name)
</div>
}
但标签未与相关的单选按钮。
but the label isn't associated with the radiobutton.
推荐答案
您的foreach
循环不产生为
属性为标签(如果您删除新{ID = p.id.ToString()}
从单选
方法,没有 ID
属性要么尽管它是默认行为,这样做可以添加。
Your foreach
loop is not generating for
attribute for the label (and if you removed new { id = p.id.ToString() }
from the RadioButton
method, no id
attribute would be added either despite it being the default behavior to do so.
当你的模型的属性不会被添加的原因的IEnumerable< T>
是符合HTML-4标准,其中指出
The reason the attributes are not added when your model is IEnumerable<T>
is to comply with the HTML-4 standards which state that
ID标记必须以字母([A-ZA-Z])
ID tokens must begin with a letter ([A-Za-z])
HtmlHelpers
生成 ID
根据名称
属性属性但更换和 [
,]
和。
与字符强调以防止的jQuery
选择冲突(如。
在 ID
属性将被解释为一个类名选择器)。在你的情况名称
是名=[0] .Name点
为集合中的第一个项目,但因为这将意味着产生 ID =_ 0__Name
(在HTML-4无效),在的HtmlHelper
只是省略了 ID
(并在标签的情况下
的
。属性
HtmlHelpers
generate the id
attribute based on the name
attribute but replace and [
, ]
and .
characters with an underscore to prevent a conflict with jQuery
selectors (e.g. a .
in an id
attribute would be interpreted as a class name selector). In your case the name
is name="[0].Name"
for the first item in the collection, but because that would mean generating id="_0__Name"
(invalid in HTML-4), the HtmlHelper
just omits the id
(and in the case of a label
, the for
attribute.
有一个简单的方法来解决这个问题是只是包装在<单选按钮;标签>
元素
A simple way to solve this is to just wrap the radio button in a <label>
element
<label>
@Html.RadioButton("name", "1", false)
<span>@p.name</span>
</label>
另一种选择是生成 ID
在单选按钮()
,并生成一个匹配的在标签
Another option is to generate the id
attribute in RadioButton()
and also generate a matching for
attribute in the label
@Html.RadioButton("name", "1", false, new { onclick = "ShowOption(this)", id = p.id })
@Html.Label(p.name, new { @for = p.id})
附注:我建议你使用stongly键入 RadioButtonFor()
和 LabelFor()
方法。
Side note: I recommend you use the stongly typed RadioButtonFor()
and LabelFor()
methods.
这篇关于MVC RadiobuttonFor剃刀如何使标签能点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!