DucDigital for ( $girl = 1; $girl < $required; $girl++ ) { echo “I love DucDigital”; }

12Jan/101

Automatic highlight menu for asp.net mvc.

For a while now I've been wondering how to work out with the menu, so that it can automatic highlight with the least amount of code. So after a while, i come up with this. There are some part which I used the language helper I wrote in previous post. Just go ahead and replace it to whatever that suit your needs.

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. There is a if check in this method, it check for both current action and method if it actually fit the link.
so if you are doing a higher level menu item, in this case, a controller menu, you can just simply compare the controller instead of both.

1
2
3
4
5
6
7
8
9
10
11
12
    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(), "<span>"+link+"</span>");
    }

And here is the actual sample usage of the code above:

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

This help a lot when you create a menu that can automatic indicate whether you are in that page or not.

  • Share/Bookmark
Comments (1) Trackbacks (0)
  1. very interesting article


Leave a comment


No trackbacks yet.