2010-12-14 66 views
9

我創建了一個頁面的路線,所以我可以與存在於我的項目數的WebForms頁我的MVC應用程序集成:MVC的MapPageRoute和ActionLink的

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

    // register the report routes 
    routes.MapPageRoute("ReportTest", 
     "reports/test", 
     "~/WebForms/Test.aspx" 
    ); 

    routes.MapRoute(
     "Default", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 
} 

這就造成一個問題,每當我在使用Html.ActionLink我的看法:

<%: Html.ActionLink("Home", "Index", "Home") %> 

當我在鏈接出現像瀏覽器加載頁面:

http://localhost:12345/reports/test?action=Index&controller=Home 

有沒有人遇到過這個?我怎樣才能解決這個問題?

回答

5

我的猜測是你需要添加一些參數選項到MapPageRoute聲明。所以如果你在WebForms目錄中有多個webforms頁面,這個效果很好。

routes.MapPageRoute ("ReportTest", 
         "reports/{pagename}", 
         "~/WebForms/{pagename}.aspx"); 

PS:你可能也想看看的RouteCollection

RouteExistingFiles屬性另一種方法是使用

<%=Html.RouteLink("Home","Default", new {controller = "Home", action = "Index"})%> 
+2

謝謝。我想避免使用RouteLink只是爲了簡潔,但我可能不得不使用它。我只是不明白爲什麼當我使用ActionLink時頁面路線與我的常規路線相匹配。 – Dismissile 2010-12-15 15:33:29

5

我剛做了一個非常類似的問題。我的解決方案是讓路由系統有理由在尋找ActionLink的匹配項時拒絕頁面路由。

具體而言,您可以在生成的URL中看到ActionLink創建兩個參數:控制器和操作。我們可以使用這些方法來使我們的「標準」路由(〜/ controller/action/id)與頁面路由不匹配。

通過用參數替換頁面路由中的靜態「報告」,我們將其稱爲「控制器」,然後添加「控制器」必須爲「報告」的約束,我們爲報告獲取相同的頁面路由,但拒絕任何帶有不是「報告」的控制器參數。

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

    // register the report routes 
    // the second RouteValueDictionary sets the constraint that {controller} = "reports" 
    routes.MapPageRoute("ReportTest", 
     "{controller}/test", 
     "~/WebForms/test.aspx", 
     false, 
     new RouteValueDictionary(), 
     new RouteValueDictionary { { "controller", "reports"} }); 

    routes.MapRoute(
     "Default", // Route name 
     "{controller}/{action}/{id}", // URL with parameters 
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
    ); 
}