css - Html 帮助器标签不显示 id

标签 css html-helper

我创建了一个复选框和复选框的标签,我使用 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>

这里存在三个问题:

  1. CSS 不会影响标签(不改变背景)
  2. 标签的标签不指向复选框,因为它无法定义复选框的 id
  3. 标签不可点击

最佳答案

解决每个问题

  1. 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 {
    ....
}

Refer fiddle

  1. 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;
}
  1. 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/

相关文章:

asp.net-mvc - MVC LINQ to SQL 表连接记录显示

css - 如何在HTML中嵌入RTSP实时流?

html - CSS使图像显示在div之外

css - 集中背景图像

ruby-on-rails - Rails image_tag 没有关闭图像标签

asp.net-mvc - 使用 HtmlHelper.BeginForm() 是如何工作的?

ruby-on-rails - 使用 simple_format 帮助器允许 id 属性

html - 如何使用[位置: fixed ]?设置dom节点的正确宽度

javascript - 如何使用<video>处理带有旋转属性的视频?

asp.net-mvc-5 - 如何编辑自定义 DisplayWithIdFor?