Go to home page mail me! RSS Feed

Adding “class” attribute to htmlAttributes of the HtmlHelper in MVC

Friday, November 27, 2009 1:22 PM

I’ve seen lots of questions on how you can add a “class” attribute to any html tag such as the “a” tag while using the HtmlHelper class in ASP.NET MVC. The problem here is “class” is a reserved keyword in .NET so you just can’t use “class” in the htmlAttributes object of the HtmlHelper class. i.e. this will work perfectly.

<%=Html.ActionLink("Log in","Login", null, new { id = "idforthislink" } %>

but this won’t

<%=Html.ActionLink("Log in","Login", null, new { id = "idforthislink", class ="red" } %>

It will error out on class. Here is the proper way of doing it.

<%=Html.ActionLink("Log in","Login", null, new { id = "idforthislink", @class="red" } %>

have fun!

DotNetKicks Image

Your Comments.

No comments posted yet.

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 4 and 1 and type the answer here:

Preview Your Comment.

 
Next entries »