2010-08-04 94 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")