Adding “active” tag to navigation list in an asp.net mvc master page

后端 未结 15 1892
渐次进展
渐次进展 2020-12-12 13:31

In the default asp.net mvc project, in the Site.Master file, there is a menu navigation list:

15条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 14:14

    Here is the version compatible with the current version of MVC4.
    I have rewritten Adam Carr's code as an extension method.

    using System;
    using System.Web.Mvc;
    using System.Web.Mvc.Html;
    using System.Web.Routing;
    
    namespace MyApp.Web {
        public static class HtmlHelpers {
            /// 
            /// Returns an anchor element (a element) that contains the virtual path of the
            /// specified action. If the controller name matches the active controller, the
            /// css class 'current' will be applied.
            /// 
            public static MvcHtmlString MenuActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName) {
                var htmlAttributes = new RouteValueDictionary();
                string name = helper.ViewContext.Controller.GetType().Name;
    
                if (name.Equals(controllerName + "Controller", StringComparison.OrdinalIgnoreCase))
                    htmlAttributes.Add("class", "current");
    
                return helper.ActionLink(linkText, actionName, controllerName, new RouteValueDictionary(), htmlAttributes);
            }
        }
    }
    

提交回复
热议问题