2013-05-13 55 views
0

是否有無論如何我可以減少重複mapRoute註冊在global.ascx文件中的多個頁面級別如下。Mvc 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 ... 

請讓我知道是否有更好的方法。

+0

嗨,如果您發現有用的答案,請將其標記爲已解決,以便其他用戶可以看到您是如何解決問題的。 – polkduran 2013-05-16 09:17:56

回答

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;