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?
HTML elements can have attributes. For example:
Here the
div
's attributes areclass
anddata-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:
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 becauseclass
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: