Wizard
Wizard

Reputation: 1162

How can I configure sub routes in MVC

I have a service in my website that loads content blocks from an external provider, from which users are are able to click links and navigate.

My routing needs to be able to handle these by calling my home controller with the request path.

For example, the url they will use to navigate will be

www../shop/hire/category/subcategory/subsubcategory/....

and if they're after a specific product:

www../shop/hire/category/subcategory/subsubcategory...?product=ABC

the constant in that, would be /shop/hire/ with the categories changing based on where you are, and the product if they have found what they are actually after.

The problem I've got, is when a link with a path like that is clicked in my application, rather than using the HomeController so I can parse the request, and call the service with the appropriate URL, I just get a 404.

I've tried adding the route:

routes.MapRoute(
        name: "Category",
        url: "shop/hire/{categories}/{product}",
        defaults: new { controller = "Home", action = "Index", categories = UrlParameter.Optional, product = UrlParameter.Optional }
    );

but this doesn't seem to have had any effect.

Upvotes: 0

Views: 329

Answers (1)

Nkosi
Nkosi

Reputation: 247153

Try using a catch all route

routes.MapRoute(
        name: "Category",
        url: "shop/hire/{*categories}",
        defaults: new { controller = "Home", action = "Index" }
    );

and in your action you can parse the value to get your categories and product

public ActionResult Index(string catagories) { ... }

Upvotes: 1

Related Questions