3

I am trying to add attributes like class, style .etc, using the razor helpers. How can I accomplish this?

Example: @Html.LabelFor(model => model.First)

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
Nation
  • 496
  • 2
  • 5
  • 22

2 Answers2

4

You need to use the New keyword and you can add HTML attributes like so:

@Html.LabelFor(model => model.First, new { @class = "test", id = "Lbl1"}))

Etc..You can keep adding HTML attributes inside the new {}.

Botonomous
  • 1,746
  • 1
  • 16
  • 39
  • You need to prefix `class` with `@` to escape it. It's a C# keyword: `new { @class = "test"...` – Mike Brind Sep 26 '13 at 19:19
  • I am getting an error with this approach. The code underline in red – Nation Sep 26 '13 at 20:10
  • the problem with this approach is that you can't place `data-` attributes – Cristi Pufu Sep 26 '13 at 20:17
  • @CristiPufu you can use data, but by using **data_***
    [See this StackOverflow Link](http://stackoverflow.com/questions/4844001/html5-data-with-asp-net-mvc-textboxfor-html-attributes)
    – Nation Sep 26 '13 at 21:05
2

@Html.LabelFor(model => model.First, new Dictionary<string, object>() { { "class", "class-name" }, { "style", "display:none" } });

Is that what u mean ?

Cristi Pufu
  • 9,002
  • 3
  • 37
  • 43