views:

352

answers:

1

I want to include a link in my SiteMaster (using Html.ActionLink) UNLESS the view that I am linking to is the current view. For example, there is no sense displaying a "Register" link when the user is already seeing the "Register" view.

In Ruby on Rails, I use the "link_to_unless_current" method to do this.

How do I duplicate this behavior in ASP.NET MVC? The best I can come up with is to set a boolean in my controller to indicate that the link should be hidden (since it is current). This seems really awkward compared to the Rails approach, so I think I must be missing something.

+7  A: 

I am not aware of such helper method in ASP.NET MVC but it should be pretty easy to roll your own:

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") %>
Darin Dimitrov