How to dynamically alter the class of an Html.ActionLink in MVC
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>
Comments
-
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 about 15 yearsagreed, 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 about 15 yearsthanks for helping me make the paradigm shift! I enjoy the clean separation this provides!