A colleague recently inquired about adding ‘class’ attribute to HTML elements being produced by HTML helpers in ASP.NET MVC. This is straightforward and well documented in the MSDN. However, it lacked examples so I thought I’d share some examples of how to use the HTML helper methods to output the HTML element attributes.
First example is of setting the ‘class’ and ‘size’ attribute of a Textbox via the HTML.TextBox() method,
<%= Html.TextBox("Title", null, new { @size="40", @class="post-title"})%>
produces the following HTML,
<input id="Title" class="post-title" type="text" value="" size="40" name="Title"/%>
Another example, this time for textarea,
<%= Html.TextArea("Body", new { @rows="20", @cols="73"})%>
produces the following HTML code,
<textarea id="Body" rows="20" name="Body" cols="73"/>