在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>
按照以上的方法设置了,但一直提示’System.Web.Mvc.HtmlHelper’ does not contain a definition for ‘MenuLink’ and no extension method ‘MenuLink’ accepting a first argument of type ‘System.Web.Mvc.HtmlHelper’ could be found (are you missing a using directive or an assembly reference?)。请楼主给点指示哈,谢谢。
你调用MenuLink扩展方法不对,第一个参数不是HtmlHelper,而是string
引用 using System.Web.Mvc.Html;