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")
@Html. ActionLink("name", "Action", "Controler", new { id= sentId, Style = "color:White" }, null);
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.
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).
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With