Variable number of routes in ASP.Net MVC

We all know about default routing mechanism of ASP.Net MVC that is how routing is works. I would call below routing mechanism as static routing. In this routing, our URL pattern is fixed. See below pic.

degaultrouting
Default route

Default route has controller name as Home and action as Index. Third part is id and we have marked it as optional. It means if someone will not provide id in URL, then still web app won’t give you any error and it will execute Index action of Home controller.

Here, id is single parameter, it may take integer/string or any other datatype based on our need.

Now, what if we want to provide multiple values in id parameter and we don’t know in advance how many then what? So let me give you example of this situation.

We need to display list of products and you need to pass all selected products in URL. So how we will pass multiple product ids or names in URL? Like below

https://example.com/Product/Mobile/Laptop
https://example.com/Product/Mobile/Laptop/HeadPhones
https://example.com/Product/Mobile/Laptop/HeadPhones/TV

etc.

Here, catch-all parameters comes into picture. We can provide as many as names in URL. See below how you can provide multiple names in URL.

catchall route
Catch all route

Note that URL route and action method’s parameter name both must be same. In our case, it is products.

controller
Action method in Product controller
catch all resulte
View result

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *