Search code examples
asp.net-mvc-3

how to set CSS attributes of label in MVC 3


I am creating a static using Html.LabelFor(...). I have to set Name attribute of the label dynamically using JQuery.


Solution

  • You can set the css class, and set inline styles and any other attribute (even non-existant ones like name) using the htmlAttributes parameter provided in one of the overloads of LabelFor

    ie

    <%: Html.LabelFor(model=>model.Title, 
                               new { style="xyz", @class="abc", @name="MyTitle" }) %>
    

    this would create a label something like:

    <label for="Title" style="xyz" class="abc" name="MyTitle">Title</label>
    

    The reason for the @ before class, is that "class" is a reserved word in c#, so you need to qualify it using the @ symbol.