ASP.NET MVC version for Ruby on Rails "link_to_unless_current"

I want to include a link in my SiteMaster (using Html.ActionLink) IF the view I'm linking to is current. For example, it makes no sense to display the "Registration" link when the user already sees the "register".

In Ruby on Rails, I use the "link _ to _ , if only _ current" method.

How to duplicate this behavior in ASP.NET MVC? The best I can think of is to set a boolean value in my controller to indicate that the link should be hidden (since it is current). This seems very inconvenient compared to the Rails approach, so I think I'm missing something.

+7
ruby-on-rails asp.net-mvc
source share
1 answer

I am not aware of such a helper method in ASP.NET MVC, but it is pretty easy to collapse:

 public static class HtmlExtensions { public static string ActionLinkUnlessCurrent(this HtmlHelper htmlHelper, string linkText, string actionName) { string currentAction = htmlHelper.ViewContext.RouteData.Values["action"].ToString(); if (actionName != currentAction) { return htmlHelper.ActionLink(linkText, actionName); } return linkText; } } 

And then use it like this:

 <%= Html.ActionLinkUnlessCurrent("Link Text", "Index") %> 
+10
source share

All Articles