← All articles
development

MVC HtmlHelper.ActionLink with Css Class

ASP.NET MVC's HtmlHelper.ActionLink chokes on class as a reserved word in htmlAttributes -- use @class instead and your CSS class renders fine.

Donn Felker

Donn Felker

2009.05.14 · 1 min read · updated July 5, 2013

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”.

Donn Felker

Written by Donn Felker

I've spent 25+ years shipping software, writing books, and running my own companies. I write about thinking clearly, working for yourself, and doing real work while AI rewrites the rules. New essays land here every week.

Get the newsletter

Keep reading