gpt4 book ai didi

asp.net-mvc - Asp.net mvc 3.0 树形结构页面自定义路由

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:34:08 25 4
gpt4 key购买 nike

我想将所有 CMS 页面 url 映射到单个 Controller (PageController) 和操作 (Details)。

如何创建自定义路由来映射所有这些 URL?

/teacher
/teacher/kindergarten
/teacher/kindergarten/1
/teacher/primary
/teacher/primary/english
/teacher/primary/language
/teacher/primary/language/chinese
/teacher/primary/math
/teacher/primary/science
/parent
/parent/kindergarten
/parent/primary1-3
/parent/primary4-6
/leader
/leader/kindergarten
/leader/kindergarten/1

最佳答案

如果您在数据库中有这些 URL,您可以在应用程序启动时映射路由:

  var pages = siteDB.Pages.ToList();
string pagePath = "";
foreach (var page in pages)
{
routeVals = new RouteValueDictionary();
constraints = new RouteValueDictionary();

routeVals.Add("controller", "page");
routeVals.Add("action", "details");

constraints.Add("path", "[a-zA-Z0-9\\-]*");

// any child pages? must add these routes before their parent pages.
var childPages = siteDB.Pages.Where(p => p.ParentPageId == page.PageId).ToList();
foreach (var childPage in childPages)
{
pagePath = BuildPath(childPage);
RouteTable.Routes.Add(new Route(pagePath, new MvcRouteHandler())
{
Defaults = routeVals,
Constraints = constraints,
DataTokens =
new RouteValueDictionary {
{ "pageid", childPage.PageId },
{ "path", pagePath }
}
});

// Any further child pages? (Only 3 levels supported)
var childSubPages = siteDB.Pages.Where(p => p.ParentPageId == childPage.PageId).ToList();
foreach (var childSubPage in childSubPages)
{
pagePath = BuildPath(childSubPage);
RouteTable.Routes.Add(new Route(pagePath, new MvcRouteHandler())
{
Defaults = routeVals,
Constraints = constraints,
DataTokens =
new RouteValueDictionary {
{ "pageid", childSubPage.PageId },
{ "path", pagePath }
}
});
}
}

此代码从数据库中获取页面,这些页面通过父 ID 链接。

这是生成每个页面的完整路径的 BuildPath 函数:

public static string BuildPath(Page page)
{
if (page.ParentPageId == 1)
{
return page.PageKey;
}
else
{
SiteDataEntities siteDB = new SiteDataEntities();
string path = page.PageKey;
Page parent = siteDB.Pages.Find(page.ParentPageId);
while (parent != null)
{
path = parent.PageKey + "/" + path;
parent = siteDB.Pages.Find(parent.ParentPageId);
if (parent.PageKey == "home") break;
}
return path;
}
}

关于asp.net-mvc - Asp.net mvc 3.0 树形结构页面自定义路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6530604/

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