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

14,303

Solution 1

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>

Solution 2

In a Razor view you can do something like this:

@model AssessmentQuestionViewModel

@{var newClass = Model.AnswerValue == 0 ? "not-answered" : string.Empty;}

<a href="@Url.Action("Index", "Home")" class="wizard-step @newClass">View Question</a>
Share:
14,303
Toran Billups
Author by

Toran Billups

Swiss Army Knife: Elixir, React &amp; Tailwind

Updated on June 03, 2022

Comments

  • Toran Billups
    Toran Billups about 2 years

    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")
    
  • Toran Billups
    Toran Billups about 15 years
    agreed, but in the case where I need to show / hide a menu option based on user credentials (webforms convert to MVC) - how can I do such in MVC?
  • Toran Billups
    Toran Billups about 15 years
    thanks for helping me make the paradigm shift! I enjoy the clean separation this provides!