這裏是提供了一個非常乾淨的方式來實現這種菜單的教程:
http://www.dev102.com/2009/04/14/creating-a-tabbed-menu-control-for-aspnet-mvc/
魔術位搞清楚一個菜單項是否是活動發生在呈現輔助方法項目:
public static class MyHtmlHelper
{
public static string TabbedMenu(this HtmlHelper helper, IEnumerable<MenuTab> tabs)
{
var route = helper.ViewContext.RequestContext.RouteData;
//This is the current controller
var controller = route.GetRequiredString("controller");
var action = route.GetRequiredString("action");
var menu = "\n\n<ul id=\"menu\">";
foreach (var tab in tabs)
{
//if the menu controller and action match current controller and action, mark it as selected
if (controller == tab.Controller && action == tab.Action)
menu += "\n\t<li>" + helper.ActionLink(tab.Text, tab.Action,
tab.Controller, new { @class = "selected" }) + "</li>";
else
menu += "\n\t<li>" + helper.ActionLink(tab.Text,
tab.Action, tab.Controller) + "</li>";
}
menu += "\n</ul>\n\n";
return menu;
}
}
MenuTab類:
public class MenuTab
{
private MenuTab(string text, string action, string controller)
{
Text = text;
Action = action;
Controller = controller;
}
public static MenuTab Create(string text, string action, string controller)
{
return new MenuTab(text, action, controller);
}
public string Text { get; private set; }
public string Action { get; private set; }
public string Controller { get; private set; }
}
用法:每控制器
<%= Html.TabbedMenu(new List<MenuTab> {
MenuTab.Create("Home", "Index", "Home"),
MenuTab.Create("About", "About", "Home"),
MenuTab.Create("Services", "Services", "Home"),
MenuTab.Create("Pricing", "Pricing", "Home"),
MenuTab.Create("Contact", "Contact", "Home")
}) %>
完美,這正是我一直在尋找。謝謝! – Anders 2010-08-05 10:34:18