在asp.net mvc中,高亮当前菜单项有很多方法,下面使用自定义Html helper来实现。这个自定义的helper会检查当前的action和链接中的action是否相等,如果相等就加上额外的css样式。

定义样式

ul#menu li
{
    float: left;
    list-style:none;
}

    ul#menu li a
    {
        background: none;
        color: #999;
        padding: 5px;
        border-radius: 15px;
        text-decoration: none;
    }

        ul#menu li a.currentMenuItem
        {
            background-color: black;
            color: white;
        }

自定义Html helper

        public static MvcHtmlString MenuLink(this HtmlHelper helper, string text, string action, string controller)
        {
            var routeData = helper.ViewContext.RouteData.Values;
            var currentController = routeData["controller"];
            var currentAction = routeData["action"];

            if (String.Equals(action, currentAction as string, StringComparison.OrdinalIgnoreCase) && String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase))
            {
                return helper.ActionLink(text, action, controller,null, new { @class = "currentMenuItem" });
            }
            return helper.ActionLink(text, action, controller);
        }

使用Html helper构建菜单

<ul id="menu">
    <li>@Html.MenuLink("Home", "Index", "Home")</li>
    <li>@Html.MenuLink("About", "About", "Home")</li>
    <li>@Html.MenuLink("Contact", "Contact", "Home")</li>
</ul>

运行效果

ASP.NET MVC 高亮当前菜单项-程序旅途