And*_*ers 2 navigation asp.net-mvc
我正在尝试学习ASP.NET MVC,我希望在当前选中的项目上突出显示菜单.我知道我之前在网络表单中做过这些(虽然我实际上并不记得当前如何,但不知何故使用网站地图).但是如何在MVC中完成呢?
在MVC中做起来应该很简单似乎是一件基本的事情?当然,我可以通过添加从菜单中的body id和li id之间耦合的CSS规则来实现它(#home #homeli [style as current]),但似乎很快会变得笨拙,特别是如果还有主导航之外的很多子菜单(在几个子页面中我在contentplaceholder中有一个子菜单.顺便说一句,我想这是在MVC中唯一的方法吗?在网页表单中,子菜单也可以通过站点地图,但我还没有看到在MVC中这样做的方法...)
有什么建议?
这是一个教程,提供了一种非常干净的方式来实现这种菜单:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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; }
}
Run Code Online (Sandbox Code Playgroud)
用法:
<%= 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")
}) %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2103 次 |
| 最近记录: |