With HTML 5 and JS frameworks heavily using data attributes within HTML tags, Razor views could cause you a headache without this little tip for attributes.
For example Data attributes have a syntax like « data-* ». If you add the hyphen within the name of an attribute in your anonymous class, Razor engine will interprets it simply as a minus sign … and won’t compile !
To add a Data attribute (or any other attribute with a hyphen within the name) within an HTML helper, you should replace the hyphen with an underscore. Hence, Razor engine will understand this and converts it to a hyphen in the HTML output.
@Html.DropDownList("Country", ViewData["Countries"] as SelectList, new { @class = "selectpicker", data_style = "btn-form-control" })
The HTML output will be:
<select id=”Country” name=”Country” class="selectpicker" data-style=”btn-form-control” />