CSS class property in ASP.NET MVC HtmlAttributes

Posted by William on Oct 9, 2009

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" }) %>