William Duffy

Glasgow Based 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" }) %>
Bookmark and Share
  Kick It on DotNetKicks.com

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

Leave a Reply