William Duffy

Glasgow Based C# ASP.NET Web Developer

CSS class property in ASP.NET MVC HtmlAttributes

When adding an ActionLink or using a similar Html helper on your C# ASP.NET MVC views you will on occasions want to pass a css class via the htmlAttributes parameter. As this is normally achieved by creating an anonymous type you may expect the following code snippet to work.

1
<%= Html.ActionLink("My Link", "MyLink", null, new { class = "test" }) %>

However, a problem arises with the class property, because class is a reserved word the compiler will throw the following error…

Compiler Error Message: CS1513: } expected

Fortunately the solution is simple. Prepend the reserved class keyword with an @ character. This lets the compiler know that you want to use the word class as a property within it’s currently applied context.

1
<%= Html.ActionLink("My Link", "MyLink", null, new { @class = "test" }) %>

Tagged as , , , , , + Categorized as ASP.NET, C#, HTML & CSS, MVC

8 Comments

  1. thanks so much this is exactly what i needed!

  2. Is there any way of adding a CSS ID to an ActionLink ?

  3. Thank you, I’ve been looking for this solution!

  4. I have yet to find an answer to this: What if you want to add multiple classes to an element?
    It doesn’t seem to take spaces like normal markup.

    Any thoughts?

  5. @Patrick Perhaps I’ve misunderstood your questing, but if you wanted to add multiple classes it’s just a case of specifying them in the anonymous object initializer – new { @class = “classOne classTwo classThree” }.

  6. @Patrick Except we are misunderstandingur question,i think i identify with william,just separate the classes with space,it works

  7. Thanks for the tip…Forgot about reserved words like Class causing these issues. Wish it was documented in the Telerik help. But at least we found it!

  8. EXACTLY what I needed! That one had me baffled. Thanks.

Leave a Reply