Try fast search NHibernate

10 November 2011

MVC3 : set active menu by controller name

Just as a “nice to have” in the default templates of MVC.

In the default CSS of MVC3 you can find some styles never applied. One of those style is about the selected menu:

ul#menu li.selected a
{
    background-color: #fff;
    color: #000;
}

In the _Layout.cshtml would be nice to have something like this:

    <script type="text/javascript">
        $(document).ready(function () {
            var controlerName = '@(ViewContext.RouteData.GetRequiredString("controller"))'.toLowerCase();
            $('ul#menu li a')
                .removeClass('selected')
                .filter(function (index) {
                    return $(this).attr('href').toLowerCase().indexOf(controlerName) != -1;
                })
                .addClass('selected');
        });
    </script>
</body>
</html>

Obviously the script can be more sophisticated but, the above, can be a simple start point to avoid some questions.

3 comments:

  1. What we should to do if our main menu contains a group of controllers? I mean that we have admin area (with or without mvc's areas) and have following controllers: UserRightsController, UsersController, etc. And we needn't to have `Rights` and `Users` menus and only `Administration`.

    ReplyDelete
  2. Because I'm talking about MVC3 templates coming with VisualStudio, what is important is the concept, which is:
    take some information from the view-context (area/controller/action) then match it with an attribute of the anchor (in this case I have used the href but is the same with "myCoolAttribute").

    ReplyDelete
  3. I personally prefer a more trivial solution for example you can add dummy class name to you body / head that is formatted as "{Controller}_{Action}"

    For each menu item add a class that represent it (i am sure you already have one to control its specific style and image)

    and not you can control the the entire UI using native CSS, just set your styling for example to set background color of active menu item

    for example
    .user_login .menu_login { background-color:red }
    .home_index .menu_home { background-color:red }

    in the above, the login menu will be colored only when the user login page is displayed

    :)

    ReplyDelete