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

后端 未结 15 1862
渐次进展
渐次进展 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:07

    Based on the previous answers, here is what my current solution is for the same issue:

    In the master page I give each li an id that corresponds to the controller and the action, since this should be known from the ActionLink. I was previously doing this with the page title but this helps with organization.

    Site.Master:

    
    

    Site.Master.cs:

    // This is called in Page_Load
    private void SetActiveLink()
    {
        string action = "" + ViewContext.RouteData.Values["controller"] + ViewContext.RouteData.Values["action"];
        var activeMenu = (HtmlGenericControl)Page.Master.FindControl("menu" + action);
    
        if (activeMenu != null)
        {
            activeMenu.Attributes.Add("class", "selected");
        }
    }
    

    It's more work than the inline code but I think it's cleaner and also lets you have actions with the same name in different controllers. So if you add more menu items with different controllers, not all actions named Index will be highlighted in the menu.

    If anyone sees issues with this approach please let me know.

提交回复
热议问题