This is a great question. I remember having to do this is ASP.NET but havent thought about it for ASP.NET MVC.
For ASP.NET MVC, you could create a user control, but I like the idea of an HTMLHelper
extension method. Taking beseku's idea from above, that would be the ultimate output of your control. The method would accept a collection of elements, and from those elements you would then be able to determine the selected page.
- Create a
MenuTab
object that has properties of DisplayText, ActionName, and ControllerName.
- Create a
System.Web.MVC.HtmlHelper
extension that takes a collection of MenuTab
as an argument, e.g. public static MvcHtmlString TabbedMenu(this HtmlHelper helper, IEnumerable<MenuTab> menuTabs)
. Note the return type of MvcHtmlString
so it works both with response.write and html.encode.
- Inside the body of the above method, you would be able to see via the
HtmlHelper
if the pages current controller and action matches the controller and action names of any of the passed in MenuTab
, and if so, build an ActionLink
that has a html class attribute set to your css class for a selected item.
Example usage in you master page would be something like:
<%: Html.TabbedMenu(new List<MenuTab> {
new MenuTab{Text="Home", ActionName="Index", ControllerName="Home"},
new MenuTab{Text="Other Page", ActionName="Index", ControllerName="Other Controller"},
new MenuTab{Text="What is this?", ActionName="About", ControllerName="Home"}
}) %>
in one that I am using, I am additionally passing in an id parameter so I could have multiple menus on the same page (think side and top navigation).