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.
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") %>
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