2013-07-26 23 views
0

我正在使用MVC 4應用程序並在route.config中映射URL 我想使用50個不同的路由名稱爲其運行一個for環路route.config這樣的事情..For Loop無法在MVC4的route.config中工作

for (int i = 1; i <= 50; i++) 
{ 


string routeChildLink = "URLRoute" + i.ToString(); 
    string pathChildLink = menuSubChild.pageid.ToString() + "/" + menu.title.Replace(" ", "_") + "/" + menuChild.title.Replace(" ", "_") + "/" + menuSubChild.title.Replace(" ", "_") + "/" + i; 
    routes.MapRoute(routeSubChildLink, pathSubChildLink, new { controller = "home", action = "index" }); 

} 

但是當我通過一個錯誤,說明運行站點爲「名爲‘URLRoute1’A路線已經是路由集合中。路線名稱必須是唯一的。」 For循環不起作用。

請幫忙。

感謝

+0

其中'routeSubChildLink','pathSubChildLink'從何而來? – jzm

+0

我沒有收到任何錯誤。讓我知道他們是如何發生的?請發佈完整代碼... –

+0

@jzm:routeSubChildLink是名稱,pathSubChildLink是URL – Shivendra

回答

0

Framework始終嘗試將請求的URL按照添加到RouteCollection的路由順序匹配到路由。

所以你應該把定製路由的默認路由之前,

public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
      for (int i = 1; i <= 50; i++) 
      { 
       string routeChildLink = "URLRoute" + i.ToString(); 
       //Custom route 
       routes.MapRoute(
            name: "Route name", 
            url: "URL with parameters", 
            defaults: new { controller = "Home", action = "MethodName" } 
           ); 
      } 

      //default route 
      routes.MapRoute(
          name: "Default", 
          url: "{controller}/{action}/{id}", 
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
         ); 
     } 

    protected void Application_Start() 
      { 
       AreaRegistration.RegisterAllAreas(); 

       RegisterGlobalFilters(GlobalFilters.Filters); 
       RegisterRoutes(RouteTable.Routes); 
      }