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

2

14

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")
Yelenayelich answered 4/6, 2009 at 17:32 Comment(0)
E
29

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>
Elfland answered 4/6, 2009 at 17:39 Comment(3)
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?Yelenayelich
For showing/hiding based on credentials, either surround with an if block or write an HtmlHelper extension method to encapsulate the logic. You can pass a value from the controller if the user is authenticated then check for that in the view.Elfland
thanks for helping me make the paradigm shift! I enjoy the clean separation this provides!Yelenayelich
T
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>
Tichon answered 19/7, 2012 at 0:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.