Mvc maproute多页面级别

时间:2013-05-13 09:33:13

标签: asp.net-mvc-3 c#-4.0 asp.net-mvc-4

无论如何,我可以减少global.ascx文件中复制mapRoute注册的数量,以获取多个页面级别,如下所示。

    routes.MapRoute("Article-level1",
                "{sluglevel1}/article/{id}/{article-title}",
                new { controller = "article", action = "detail", id = UrlParameter.Optional });


routes.MapRoute("Article-level2",
                "{sluglevel1}/{sluglevel2}/article/{id}/{article-title}",
                new { controller = "article", action = "detail", id = UrlParameter.Optional });

routes.MapRoute("Article-level3",
                "{sluglevel1}/{sluglevel2}/{sluglevel3}/article/{id}/{article-title}",
                new { controller = "article", action = "detail", id = UrlParameter.Optional });

... more levels 4 to 10 ...

如果有更好的方法,请告诉我。

2 个答案:

答案 0 :(得分:0)

您可以浏览“Catch-all”路线参数:Handling a Variable Number of Segments in a URL Pattern

但您需要将路线的结构更改为以下内容:

"article/{id}/{article-title}/{*sluglevels}"

答案 1 :(得分:0)

你可以做一个简单的循环,动态生成你的路线:

int levelCount = 5;

for (int i = 1; i <= levelCount; i++)
{
    string routeName = "Article-level" + i;

    IEnumerable<string> levels = Enumerable.Range(1, i).Select(r => string.Format("{{sluglevel{0}}}", r));
    string url = string.Join("/", levels);
    url += "/article/{id}/{article-title}";

    routes.MapRoute(routeName, url,
        new { controller = "article", action = "detail", id = UrlParameter.Optional });
}

您需要导入System.LinqSystem.Collections.Generic

using System.Linq;
using System.Collections.Generic;