2012-04-28 150 views
0

喜歡的網址:ASP.NET MVC3自定義路由映射?

/query/test/p1s1c1 

的動作是:

public ActionResult Test(int price = 1, int size = 1, int category = 1) 
{ 
    ViewBag.param = "price:" + price + "size:" + size + "category" + category; 
    return View(); 
} 

我的路由映射是:

routes.MapRoute(
    "Query", // Route name 
    "Query/test/p{price}s{size}c{category}", 
    new { controller = "Query", action = "Test", price = UrlParameter.Optional, size = UrlParameter.Optional, category = UrlParameter.Optional }, 
    new { price = @"\d+", size = @"\d*" , category = @"\d*" } // Parameter defaults 
    ); 

,但它不能正常工作,誰可以幫幫我嗎?

回答

1

當框架處理URL請求時,它會嘗試將請求的URL與Routes的順序相匹配的路由添加到RouteCollection

所以,把你的路線之前的默認路由,它應該工作:

routes.MapRoute(
       "Query", // Route name 
       ///... 
       ); 

routes.MapRoute(
       "Default", // Route name 
       ///... 
       ); 

現在用的網址:/query/test/p2s2c2執行的測試動作將有參數:price = 2, size = 2, category = 2

你可以閱讀更多關於How URLs Are Matched to Routes

0

試試這個...

routes.MapRoute(
    "Query", // Route name 
    "Query/test/{price}/{size}/{category}", 
    new { controller = "Query", action = "Test", price = UrlParameter.Optional, size = UrlParameter.Optional, category = UrlParameter.Optional }, 
    new { price = @"\d+", size = @"\d*" , category = @"\d*" } // Parameter defaults 
    ); 

和默認路由後....