ASP.NET MVC - style list item based on controller

后端 未结 1 512
灰色年华
灰色年华 2020-12-08 09:08

My ultimate goal is to have a menu that adds a class to the list item that associates with the current page I am on.

So I have it set up such that each controller wi

1条回答
  •  無奈伤痛
    2020-12-08 09:39

    In a recent project of mine I did it using HtmlHelper extensions and getting data from the ViewContext.RouteData.Values collection.

    So building off a simple extension like this:

    public static string OnClass(this HtmlHelper html, bool isOn)
    {
        if (isOn)
            return " class=\"on\"";
    
        return string.Empty;
    }
    

    You can build up any number of combinations, e.g.

    Just testing the current action:

    public static string OnClass(this HtmlHelper html, string action)
    {
        string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
    
        return html.OnClass(currentAction.ToLower() == action.ToLower());
    }
    

    Testing for a number of actions:

    public static string OnClass(this HtmlHelper html, string[] actions)
    {
        string currentAction = html.ViewContext.RouteData.Values["action"].ToString();
    
        foreach (string action in actions)
        {
            if (currentAction.ToLower() == action.ToLower())
                return html.OnClass(true);
        }
    
        return string.Empty;
    }
    

    Testing for action and controller:

    public static string OnClass(this HtmlHelper html, string action, string controller)
    {
        string currentController = html.ViewContext.RouteData.Values["controller"].ToString();
    
        if (currentController.ToLower() == controller.ToLower())
            return html.OnClass(action);
    
        return string.Empty;
    }
    

    Etc, etc.

    Then you simply call it in your view(s) like so

    • >Blah
    • >Blah
    • >Blah
    • >Blah

    Which ever way you look at it, HtmlHelper extensions are your friend! :-)

    HTHs
    Charles

    0 讨论(0)
提交回复
热议问题