ASP.NET MVC HtmlHelper methods and CSS class

ASP.NET MVC 4 Comments

If you in ASP.NET MVC use a Html helper method to render out e.g. an input box:

<% = Html.TextBox("name")  %>

Sometimes you might need to add an CSS class attribute to your input box (this should be a fairly standard thing). For this there exist overload methods that takes a “htmlAttributes” parameter of type object. Now my experience with this is somewhat similar to Ayende Rahien experience – although I have not begun banging my head against the wall out of frustration. This is not a rant, I love ASP.NET MVC, I just had an experience with something simple that was hard to figure out because of some of the design decisions – not that they are bad, they can just be confusing – especially with the lack of documentation at the current stage (yes, I know it is just a beta). So if you try this:

<% = Html.TextBox("name", null, new{ class = "required"})  %>

You will (of course) get a compiler error, since “class” is a keyword and cannot be used like this. So how do you specify the class? Well, like this:

<% = Html.TextBox("name", null, new{ @class = "required"})  %>

Just for future reference :)

4 Responses to “ASP.NET MVC HtmlHelper methods and CSS class”

  1. ASP.NET MVC Archived Blog Posts, Page 1 Says:
    November 21st, 2008 at 17:02

    [...] to VoteASP.NET MVC HtmlHelper methods and CSS class (11/19/2008)Wednesday, November 19, 2008 from noseyIf you in ASP.NET MVC use a Html helper method to render out [...]

  2. TomNo Gravatar Says:
    December 9th, 2008 at 6:39

    Thanks, I’ve been looking for the answer to this!

  3. Dimi3No Gravatar Says:
    January 21st, 2009 at 12:00

    Thanks!

  4. Htmlhelpers Css Classes - asp.net mvc « EricDotNet Says:
    January 29th, 2009 at 17:18

    [...] Thanks to this blogpost for the answer: http://blog.veggerby.dk/2008/11/19/aspnet-mvc-htmlhelper-methods-and-css-class/ [...]

Leave a Reply

Icons by N.Design Studio. Designed By Ben Swift. Powered by WordPress, Search Optimization and Free WordPress Themes
Entries RSS Comments RSS Log in