Donn Felker

Not A Subscriber?

Join thousands of people who build and refuse to get left behind. One message a week on building, using AI as an accelerator, and staying sharp in the new AI frontier.

Receive one free message a week

May 14, 2009 Donn Felker · updated July 5, 2013

MVC HtmlHelper.ActionLink with Css Class

When using the MVC helpers (namely the HtmlHelper class in this example) you have to be aware of what you’re typing into the htmlAttributes object (which is an overload of the Action method on that class).

Passing in values via a view is usually as simple as (Im’ using spark here):

${Html.ActionLink(“Foo”, “Foo”, null, new { class = “active” } )}

This works great, however … if you’re using the HtmlHelper in a .cs file you might run into this issue …

return html.ActionLink(“Comments”, “index”, new {area = “Story”, controller = “Story”, Guid = guid},new { class = cssclass});

THe problem is that last little part:

class = cssclass

The problem is “class” is a reserved word.

How do you get around this issue?

By adding an ‘@’ symbol to the text so it looks like this:

return html.ActionLink(“Comments”, “index”, new {area = “Story”, controller = “Story”, Guid = guid},new { @class = cssclass});

Now everything is golden. Your code will compile and the output will be “class”, not “@class”.