Search code examples
asp.net-mvcroutesasp.net-mvc-controller

How to Combine two controllers and then Action in mvc


I am making an eCommerce website it has
Home Controller
Categories Controller
Products Contoller

Now i want is when i click on Categories route should be like this

www.domain.com/Categories/

when i click on Products route should be like this

www.domain.com/Products/

And when i go to products like phones,pendrive, or TV the route should go like

 www.domain.com/Categories/Products/pendrive

just because pendrive come from Products and Products comes from Categories so i want to combine two controllers so i can get the required route

Tried something like this but didn't worked

routes.MapRoute(
                name: "Default1",
                url: "Categories/{controller}/{action}/{id}",
                defaults: new { controller = "Products", action = "Index", id = UrlParameter.Optional}
            );

Solution

  • You can create a route with same constraints like this:

    routes.MapRoute(name: "Product",
                    url: "Categories/Product/{id}",
                    defaults: new { controller = "Products", action = "Index", id = UrlParameter.Optional});
    

    Just make sure this is registered before the default route.