ASP.net MVC - Navigation and highlighting the "current" link
Check out this blog post
It shows how to create an HTML Extension that you call instead of the usual Html.ActionLink
The extension then appends class="selected"
to the list item that is currently active.
You can then put whatever formatting/highlighting you want in your CSS
EDIT
Just adding some code to rather than just a link.
public static class HtmlHelpers
{
public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName
)
{
string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
if (actionName == currentAction && controllerName == currentController)
{
return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "selected" });
}
return htmlHelper.ActionLink(linkText, actionName, controllerName);
}
}
Now you need to define your selected
class in your CSS and then in your views add a using
statement at the top.
@using ProjectNamespace.HtmlHelpers
And use the MenuLink
instead of ActionLink
@Html.MenuLink("Your Menu Item", "Action", "Controller")
You could do this by using "data-" attributes to identify the container(s) then using jQuery change CSS class of the link, like the following:
<div class="..." data-navigation="true">
<ul class="...">
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
<script>
$(function () {
$("div[data-navigation='true']").find("li").children("a").each(function () {
if ($(this).attr("href") === window.location.pathname) {
$(this).parent().addClass("active");
}
});
});
</script>