giorgian
giorgian

Reputation: 3825

ASP.NET MVC custom routes with optional args

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:

Upvotes: 1

Views: 2379

Answers (3)

Mark
Mark

Reputation: 6081

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?

Upvotes: 0

Hannoun Yassir
Hannoun Yassir

Reputation: 21202

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

Upvotes: 1

davethecoder
davethecoder

Reputation: 3932

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

Upvotes: 0

Related Questions