Search code examples
asp.net-mvcrazorrazor-declarative-helpers

What is the "HTML attributes" parameter?


The following sample:

@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })

appears to be using the second overload of the LabelFor method where the second parameter, htmlAttributes, is documented as

An object that contains the Html attributes for the element

What does the term "HTML attributes" mean and what is the syntax that can be used for this object?


Solution

  • HTML elements can have attributes. For example:

    <div class="some-css-class" data-foo="bar" />
    

    Here the div's attributes are class and data-foo.

    Razor's various HTML helper functions that accept an htmlAttributes argument translate the provided object to attributes.

    You can utilize this using an anonymous type where its properties are translated to attributes names, and their values to the respective attribute's value.

    For example:

    new
    {
        @class = "some-css-class",
        data_foo = "bar"
    }
    

    This will translate to the attributes shown above.

    Underscores in property names get translated to dashes (How to specify data attributes in razor, e.g., data-externalid="23151" on @this.Html.CheckBoxFor(...)), and the @ before @class is required because class is a reserved keyword that can't be used without escaping it with an @ (How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?).

    There's also an overload accepting IDictionary<string, object> htmlAttributes, so you could instead pass a dictionary as well:

    new Dictionary<string, object>
    {
        { "class", "some-css-class" },
        { "data-foo", "bar" }
    }