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.
Recent Posts
- Open selling Vbulletin 3 4x and VbSeo license
- Automatic change DNS for Facebook
- New chrome!
- Memcached and Asp.net mvc
- Cache individual object in asp.net mvc
Recent Comments
- Malvern on JUSTHOST SCAM, dirty and fraud
- jim greene on JUSTHOST SCAM, dirty and fraud
- Ta Duy Duc on JUSTHOST SCAM, dirty and fraud
- Malvern on JUSTHOST SCAM, dirty and fraud
- DucDigital on Noob guide to Globalization in Asp.net MVC
Categories
- Blog (26)
- Programing (11)
- Asp.net MVC (8)
- Python (1)
- SQL (3)
Tags
Blogroll
Spam cleared
Who's Online
- 0 Members
- 5 Guests