The htmlAttributes parameter is used a lot in HtmlHelper functions in your MVC views. These are great… however, what about when you want to set the class attribute or create a custom data-* attribute?
In C#, class is a reserved word and hyphens (-) are forbidden in variable names – so how can we define them in a dynamic object?
Fortunately, there are work-arounds. (phew!)
- Reserved words can be prefixed with an apetail (@ – ‘apetail’ is my new favourite word for the ‘at sign’)
- Hyphens (-) in data attributes can be replaced with underscores (_). These are swapped out for hyphens when compiled as HTML.
Example
@Html.DropDownList("ddlName", list, new { @class = "myDropDown", data_val= true, data_val_required = "Please select a value."})
becomes
...
Can’t find the MSDN documentation for this. If anyone does, please post a comment!