我创建了一个复选框和复选框的标签,我使用 html 助手来执行此操作:
@Html.CheckBoxFor(m=>m[i].checkExport)
@Html.LabelFor(m=>m[i].checkExport)
要修改标签,我在CSS文件中写道:
input[type="checkbox"] + label {
background: url('images/delete.png') no-repeat;
height:17px;
}
input[type="checkbox"]:checked + label {
background: url('images/delete.png') no-repeat;
height:17px;
}
这是自动生成的代码:
<input data-val="true" data-val-required="The checkExport field is required." name="[0].checkExport" type="checkbox" value="true">
<input name="[0].checkExport" type="hidden" value="false">
<label for="">checkExport</label>
这里存在三个问题:
- CSS 不会影响标签(不改变背景)
- 标签的标签不指向复选框,因为它无法定义复选框的 id
- 标签不可点击
最佳答案
解决每个问题
- CSS doesn't effect to label (do not change the background)
如果您检查生成的 html,您将看到 CheckBoxFor()
助手生成 2 个输入,<input type="checkbox" ..>
接下来是 <input type="hidden" ..>
最后是 <label>
元素。您的 css 选择器 ( input[type="checkbox"] + label
) 试图在 input[type="checkbox"]
之后立即查找标签元素。由于中间隐藏输入,它不存在。一种选择是使用 Following-sibling combinator
<div>
@Html.CheckBoxFor(m => m[i].checkExport)
@Html.LabelFor(m => m[i].checkExport)
</div>
input[type="checkbox"] ~ label {
....
}
- The label for tag do not point to checkbox because it can not defind (sic) id of checkbox
这是符合先前 html 规范的 html 帮助程序的一个不幸的副作用。
html 帮助程序生成 id
属性名称中的属性,但为了避免与 jQuery 冲突,请替换任何 .
, [
和]
带下划线的字符 ( _
)。在你的情况下[0].checkExport
将变成_0__checkExport
.
但是在 HTML 4一个id
属性需要以字母开头,因此这将是无效标记,因此 html 帮助程序只是从生成的标记中忽略该属性。您可以查看source code here ,相关代码部分是
if (!Html401IdUtil.IsLetter(firstChar))
{
// the first character must be a letter
return null;
}
- The label is not clickable
这与第 2 点相关,因为 id
未为复选框生成属性,因此标签元素没有有效的 for
指向关联复选框的属性。
解决此问题的一种方法是使用包含集合属性的 View 模型,例如
public class MyViewModel
{
public List<myModel> MyCollection { get; set; }
}
并在 View 中
@model yourAssembly.MyViewModel
....
for (int i= 0; i < Model.MyCollection.Count; i++)
{
@Html.CheckBoxFor(m => m.MyCollection[i].checkExport)
@Html.LabelFor(m => m.MyCollection[i].checkExport)
您的输入现在将通过 id
生成属性和标签将包含关联的 for
属性与复选框关联,因此“可点击”。
<input type="checkbox" id="MyCollection_0__checkExport" name="MyCollection[i].checkExport" ../>
...
<label for="MyCollection_0__checkExport">checkExport</label>
关于css - Html 帮助器标签不显示 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315906/