【问题标题】:Label with extra attributes using ASP.NET HTML Helpers使用 ASP.NET HTML Helpers 带有额外属性的标签
【发布时间】:2023-12-14 02:31:02
【问题描述】:

我想知道是否可以使用 HTML Helpers 生成下面的标签标签:

<label class="myClass" attr1="attr1Value" attr2="attr2Value" attr3="attr3Value">labelText</label>

它基本上是一个具有 3 个额外属性的标准标签标签。

【问题讨论】:

    标签: html asp.net html-helper


    【解决方案1】:

    可以使用@Html.Label@Html.LabelForhtmlAttributes参数

    @Html.Label("YourLabel", new { attr1 = "attr1Value", attr2 = "attr2Value" })
    

    使用class或其他保留字时使用@

    @Html.Label("YourLabel", new { @class = "classname" })
    

    当使用带有破折号- 的属性时,例如数据属性,使用下划线_ 最终被转换为破折号-

    @Html.Label("YourLabel", new { data_url = "myurl" })
    

    但是,我认为在Html.Label 中支持htmlAttributesHtml.LabelFor 仅在 MVC4 中添加,用于早期版本的 MVC 您可以编写自己的扩展方法。

    How to extend MVC3 Label and LabelFor HTML helpers?

    【讨论】:

      【解决方案2】:

      使用 HtmlHelper 可以将自定义属性添加到任何元素。

      @Html.Label("Content", new { attr1= "attr1" })
      

      但您需要将 @ 添加到作为关键字的属性,例如类

      【讨论】:

        最近更新 更多