2010-08-04 88 views
2

我想学习ASP.NET MVC,并且我想让菜单高亮显示当前选中的项目。我知道我之前用网页形式做过这件事(尽管我现在实际上并没有记住目前的情况,但以某种方式与网站地图)。但是这怎么能在MVC中完成呢?ASP.NET MVC和导航

这似乎是这样一个基本的东西,它应该很容易在MVC做?当然,我可以通过在菜单(#home #homeli [style as current])中添加身体标识和li id之间的CSS规则来做到这一点,但似乎很快就会变得笨拙,特别是如果还有除了主导航之外,还有很多子菜单(在几个子页面中,我在contentplaceholder中有一个子菜单)BTW,我想这是在MVC中完成它的唯一方法吗?在Web窗体中,子菜单也可以通过网站地图,但我还没有看到在MVC中这样做的方法...)

有什么建议吗?

回答

8

这里是提供了一个非常干净的方式来实现这种菜单的教程:

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") 
}) %> 
+0

完美,这正是我一直在寻找。谢谢! – Anders 2010-08-05 10:34:18

0

菜单项

@{ 
    var currentController = (string)ViewContext.RouteData.Values["controller"]; 

    Func<string, object> htmlAttributesFactory = 
     controller => currentController == controller ? new {@class = "selected"} : null; 

    Func<string, string, MvcHtmlString> menuItemFactory = 
     (title, controller) => 
     Html.RouteLink(
      title, 
      new {controller}, 
      htmlAttributesFactory(controller)); 


} 

@menuItemFactory("Home", "Home") 
@menuItemFactory("Pending", "Pending")