How to dynamically alter the class of an Html.ActionLink in MVC

Toran Billups picture Toran Billups · Jun 4, 2009 · Viewed 14.2k times · Source

I'm looking for a way to alter the class of an ActionLink in the controller based on specific criteria (not found in the model so I can't write a conditional in the view itself). But i can't seem to find the ViewData("name") that allows me to work w/ this element (I assume this is possible, but I'm missing something).

I have an html helper like so in my view

<%=Html.ActionLink("View", "Index", "Home")%>

But in my controller I'm not sure how to reference this, like the below to add an attribute like class or onclick.

ViewData("View").attributes.add("class", "active")

Answer

John Sheehan picture John Sheehan · Jun 4, 2009

You don't set CSS attributes from the controller since that's a concern of the view. You can add HTML attributes to the ActionLink like this:

 <%=Html.ActionLink("View Cases", "Index", "Home", new { @class="active" })%>

Alternately you can build your anchors "manually":

 <a href="<%=Url.Action("Index", "Home")%>" class="active">View Cases</a>

Or if you need to conditionally set the active class:

 <% var activeClass = someCondition ? "active" : ""; %>
 <a href="<%=Url.Action("Index", "Home")%>" class="<%=activeClass%>">View Cases</a>