views:

1904

answers:

1

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")
+8  A: 

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>
John Sheehan
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
Edited with more examples.
John Sheehan
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.
John Sheehan
thanks for helping me make the paradigm shift! I enjoy the clean separation this provides!
Toran Billups