gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 和导航

转载 作者:行者123 更新时间:2023-12-02 07:13:27 25 4
gpt4 key购买 nike

我正在尝试学习 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;
}
}

菜单选项卡类:

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

关于asp.net-mvc - ASP.NET MVC 和导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3410425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com