Navigation menu with highlight in Asp.NET MVC?

后端 未结 7 923
广开言路
广开言路 2021-02-14 15:31

It\'s a simple question. How did stackoverflow do their menu in Asp.net MVC, with highlight on what page we are on.

7条回答
  •  我寻月下人不归
    2021-02-14 16:17

    For the purpose of this, i've writen some code down, there are some part that using my custom extension like Language, go ahead and use it, just ignore the minor part.

    This one i place on top of my Partial that contain the menu to get the action and controller, so that i can pass this to the extension.

    <%  string currentAction = ViewContext.RouteData.Values["action"].ToString();
        string currentController = ViewContext.RouteData.Values["controller"].ToString(); %>
    

    This is the sidebar Item, basically this will generate a "li" tag with a link and your custom class to indicate whether the link is currently used in the page / highlight.

    public static string SidebarItem(this System.Web.Mvc.HtmlHelper html, string currentAction, string currentController, string action, string controller, string languageKey, params object[] args)
    {
        TagBuilder tb = new TagBuilder("li");
        if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) && string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
        {
            tb.GenerateId("activemenu");
        }
        string text = html.Language(languageKey, args);
        string link = html.ActionLink(text, action, controller).ToHtmlString();
        tb.SetInnerText("{0}");
        return String.Format(tb.ToString(), ""+link+"");
    }
    

    and here is the actual usage of the code above

    <%= Html.SidebarItem(currentAction, currentController, "index", "home", "index") %>
    

提交回复
热议问题