Custom ActionLink helper that knows what page you're on
I have a small MVC site that uses the Html.ActionLink helper for a navbar. One thing I would like to change is that the default ActionLink will render out an html link to a page even 开发者_C百科if that is the current page.
For example, it creates a link like this:
<a href="/myUrl">Some title...</a>
even if you're already on /myUrl. It would be nice if it would disable that link and maybe insert a special CSS class to show the currently visited page, like this:
<a href="#" class="currentPageCSS">My Url</a>
<a href="/someOtherUrl">Some Other Url</a>
This problem must have been encountered before on loads of MVC sites, so I'm curious to know how other people have tackled it.
This seems like a good scenario to roll a custom HTML helper. So let's roll it:
public static class LinkExtensions
{
public static MvcHtmlString MyActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller
)
{
var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
if (action == currentAction && controller == currentController)
{
var anchor = new TagBuilder("a");
anchor.Attributes["href"] = "#";
anchor.AddCssClass("currentPageCSS");
anchor.SetInnerText(linkText);
return MvcHtmlString.Create(anchor.ToString());
}
return htmlHelper.ActionLink(linkText, action, controller);
}
}
and inside your view:
<%= Html.MyActionLink("hello foo", "Index", "Home") %>
<%= Html.MyActionLink("hello bar", "About", "Home") %>
...
and depending on where you are the helper will generate the proper anchor.
精彩评论