0

I would like to know if it's possible to generate the label tag below using HTML Helpers:

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

It's basically a standard label tag having 3 extra attributes.

Nope
  • 22,147
  • 7
  • 47
  • 72
Platus
  • 1,753
  • 8
  • 25
  • 51

2 Answers2

1

You can use the htmlAttributes parameter of @Html.Label or @Html.LabelFor

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

When using class or other reserved words use at @

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

When using attributes with dashes -, such as data attributes, use underscores _ which end up being converted to dashes -

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

However, I think support for htmlAttributes in Html.Label and Html.LabelFor was only added in MVC4, for earlier versions of MVC you can write your own extension method.

How to extend MVC3 Label and LabelFor HTML helpers?

Community
  • 1
  • 1
Nope
  • 22,147
  • 7
  • 47
  • 72
0

Using the HtmlHelper its possible to add custom attributes to any Element.

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

but you need to add @ to attributes that are keywords e.g. class

J-H
  • 1,795
  • 6
  • 22
  • 41