2009-09-10 52 views
1

我想要一個包含兩個可選參數的Route;我以爲以下將工作:帶有可選參數的ASP.NET MVC自定義路由

routes.MapRoute(
    "ProductForm", 
    "products/{action}/{vendor_id}_{category_id}", 
    new { controller = "Products", action = "Index", vendor_id = "", category_id = "" }, 
    new { action = @"Create|Edit" } 
); 

但如果同時提供了vendor_idcategory_id它只能;使用RouteDebug我看到/products/create/_3不會觸發我的路線,所以我加了其他兩條路線:

routes.MapRoute(
    "ProductForm1", 
    "{controller}/{action}/_{category_id}", 
    new { controller = "Home", action = "Index", category_id = "" }, 
    new { controller = "Products", action = @"Create|Edit" } 
); 

routes.MapRoute(
    "ProductForm2", 
    "{controller}/{action}/{vendor_id}_", 
    new { controller = "Home", action = "Index", vendor_id = "" }, 
    new { controller = "Products", action = @"Create|Edit" } 
); 

所以,問題:

  • 使用三個途徑,使路線的唯一途徑與可選參數?

  • 這些URL是否正確,也就是說,你會建議一個更好的方法來做到這一點?

回答

1

你爲什麼不試圖給VENDOR_ID默認值(如果沒有指定,即0),那會幫助你逃脫一條路線

routes.MapRoute("ProductForm","products/{action}/{vendor_id}_{category_id}", 
new { controller = "Products", action = "Index", vendor_id = "0", category_id = "" }, 
new { action = @"Create|Edit" }); 
0

對我來說很好,但我會做一點點不同:

routes.MapRoute(
"ProductForm1", 
"product/category/{category_id}", 
new { controller = "Home", action = "Index", category_id = "" }, 
new { controller = "Products", action = @"Create|Edit" } 

);

然後

routes.MapRoute(
"ProductForm1", 
"product/details/{product_id}", 
new { controller = "Home", action = "Index", product_id = "" }, 
new { controller = "Products", action = @"Create|Edit" } 

);

那麼你的類可以如下:

ActionResults Index(){} 
ActionResults Index(int category_id){// get categories} 
ActionResults Index(int product_id){ // get products} 

但那只是我

0

你可以嘗試這樣的:

routes.MapRoute( 
"ProductForm", 
"products/{action}/{arg1}/{arg1_id}/{arg2}/{arg2_id}",  
new { controller = "Products", action = "Index", arg1 = "", arg2 = "", arg1_id = "", arg2_id = "" }, 
new { action = @"Create|Edit" }); 

那麼你會在你的ActionResult方法來檢查ARG1和ARG2並確定至極參數來創建一些邏輯已經被通過

您ActionLink的網址是這樣的:

/products/create/vendor/10 
/products/create/category/20 
/products/create/vendor/10/category/20 
/products/create/category/20/vendor/10 

我個人不喜歡這是因爲路線看起來不太乾淨,但應該給你我想你想要達到的目標?