MVC with Bootstrap Navbar - Set Selected Item to Active

后端 未结 7 1544
抹茶落季
抹茶落季 2020-12-13 10:05

I\'m learning Bootstrap and can\'t get the selected item into an \"active\" state. The active state remains on the default item. The newly selected/clicked item changes to

7条回答
  •  星月不相逢
    2020-12-13 10:41

    Simply you can do this in any view

    
    

    After you add this method to a new class or existing HtmlExtensions class

    public static class HtmlExtensions
    {
        public static MvcHtmlString NavigationLink(this HtmlHelper html, string linkText, string action, string controller, object routeValues=null, object css=null)
        {
            TagBuilder aTag = new TagBuilder("a");
            TagBuilder liTag = new TagBuilder("li");
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(css);
            string url = (routeValues == null)?
                (new UrlHelper(html.ViewContext.RequestContext)).Action(action, controller)
                :(new UrlHelper(html.ViewContext.RequestContext)).Action(action, controller, routeValues);
    
            aTag.MergeAttribute("href", url);
            aTag.InnerHtml = linkText;
            aTag.MergeAttributes(htmlAttributes);
    
            if (action.ToLower() == html.ViewContext.RouteData.Values["action"].ToString().ToLower() && controller.ToLower() == html.ViewContext.RouteData.Values["controller"].ToString().ToLower())
                liTag.MergeAttribute("class","active");
    
            liTag.InnerHtml = aTag.ToString(TagRenderMode.Normal);
            return new MvcHtmlString(liTag.ToString(TagRenderMode.Normal));
        }
    }
    

提交回复
热议问题