views:

482

answers:

3

I want a Route with two optional args; I thought the following would work:

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

But it only works when both vendor_id and category_id are provided; using RouteDebug I see that /products/create/_3 doesn't trigger my route, so I added other two routes:

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" }
);

So, the questions:

  • Is using three routes the only way to make a route with optional args?

  • Are these URLs ok or not, that is, would you suggest a better way to do this?

A: 

looks good to me but i would do it a little different:

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

);

and then

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

);

then your class can be as follows:

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

but thats just me

minus4
A: 

Why don't you try to give vendor_id a default value (if it is not specified i.e 0) that would help you get away with one route

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

you could try it like this:

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" });

Then you would create some logic in your actionresult method to check arg1 and arg2 and identify wich argument has been passed in.

your actionlink urls would look like this:

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

Personally i dont like this as the route doesn't seem very clean but should give you what i think your looking to achieve?

Mark