Adding HTML attributes via HTML helpers in ASP.NET MVC

November 17, 2009 · 4 comments

in ASP.NET MVC,CSS,HTML

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"/>
  • Jack

    how to add data-hello=”goodbye” ???

    • Bikal Gurung

      Hi Jack,

      For HTML 5 data attributes you need to use the underscore. for eg new {data_hello="goodby"}

    • Anonymous

      Hi Jack,

      For HTML 5 data attributes you need to use the underscore. for eg new {data_hello="goodby"}

      • http://www.webglnow.com/ ????

        But HTML Code:

Previous post:

Next post: