Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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")
like image 338
Toran Billups Avatar asked Jun 04 '09 17:06

Toran Billups


People also ask

How do you change the ActionLink color in HTML?

@Html. ActionLink("name", "Action", "Controler", new { id= sentId, Style = "color:White" }, null);

What is HTML ActionLink in MVC?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

How do I pass an object in ActionLink?

If you need to pass through the reference to an object that is stored on the server, then try setting a parameter of the link to give a reference to the object stored on the server, that can then be retrieved by the action (example, the Id of the menuItem in question).


2 Answers

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>
like image 147
John Sheehan Avatar answered Oct 24 '22 10:10

John Sheehan


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>
like image 37
Leniel Maccaferri Avatar answered Oct 24 '22 11:10

Leniel Maccaferri