2014-03-12 116 views
0

我想在MVC項目中路由一個鏈接。在ASP.NET中的路線MVC

我嘗試了兩種方法:

public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

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

     //method1 
     // routes.MapPageRoute("SchoolPage", "School", "~/home", false); 

     //method2 
     routes.MapRoute(name: "SchoolPage",url: "School", defaults: new { controller = "Home", action = "Index" }); 
    } 

對於這兩種方法,我得到的錯誤:

HTTP 404。您正在查找的資源(或它的一個依賴項)可能已被刪除,名稱已更改,或暫時不可用。請檢查以下網址並確保它拼寫正確。

+3

嘗試首先指定'SchoolPage'路線。 –

回答

1

您需要先指定自定義路線。默認路由沒有約束,因此它將匹配任何URL。當您提出請求http://example.org/School時,ASP.NET MVC將使用默認路由查找名爲SchoolController的控制器。您必須首先將它放在默認路線之前,確保它與SchoolPage路線相匹配。

public static void RegisterRoutes(RouteCollection routes) 
{ 
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

    routes.MapRoute(name: "SchoolPage",url: "School", defaults: new { controller =  "Home", action = "Index" }); 

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

} 
+0

謝謝!它像一個魅力! – POIR