Conditionally add htmlAttributes to ASP.NET MVC Html.ActionLink
Asked Answered
I

1

10

I'm wondering if it's possible to conditionally add a parameter in a call to a method.

For example, I am rendering a bunch of links (six total) for navigation in my Site.Master:

<%= Html.ActionLink("About", "About", "Pages") %> | 
<%= Html.ActionLink("Contact", "Contact", "Pages") %>
<%-- etc, etc. --%>

I'd like to include a CSS class of "selected" for the link if it's on that page. So in my controller I'm returning this:

ViewData.Add("CurrentPage", "About");
return View();

And then in the view I have an htmlAttributes dictionary:

<% Dictionary<string,object> htmlAttributes = new Dictionary<string,object>();
   htmlAttributes.Add("class","selected");%>

Now my only question is how do I include the htmlAttributes for the proper ActionLink. I could do it this way for each link:

<% htmlAttributes.Clear();
   if (ViewData["CurrentPage"] == "Contact") htmlAttributes.Add("class","selected");%>
<%= Html.ActionLink("Contact", "Contact", "Pages", htmlAttributes) %>

But that seems a little repetitive. Is there some way to do something like this psuedo code:

<%= Html.ActionLink("Contact", "Contact", "Pages", if(ViewData["CurrentPage"] == "Contact") { htmlAttributes }) %>

That's obviously not valid syntax, but is there a correct way to do that? I'm open to any totally different suggestions for rendering these links. I'd like to stay with something like ActionLink that takes advantage of using my routes though instead of hard coding the tag.

Ibnsina answered 13/5, 2010 at 4:12 Comment(0)
C
15

Here are three options:

<%= Html.ActionLink("Contact", "Contact", "Pages", 
         new { @class = ViewData["CurrentPage"] == "Contact" ? "selected" : "" }) %>

<%= Html.ActionLink("Contact", "Contact", "Pages", 
         ViewData["CurrentPage"] == "Contact" ? new { @class = "selected" } : null) %>

<a href="<%=Url.Action("Contact", "Pages")%>" 
   class="<%=ViewData["CurrentPage"] == "Contact" ? "selected" : "" %>">Contact</a>
Canaveral answered 13/5, 2010 at 4:16 Comment(2)
I find that this doesn't work for the disabled attribute, since the browser disables html elements for the case of disabled="". Writing your own html helper method seems to be the only solution for that case .Courtney
As of MVC 4, you can set any attribute to null and it will not render the attribute at all.Ossy

© 2022 - 2024 — McMap. All rights reserved.