0

I have an ASP.NET MVC 5 project and I want to handle some complex routes.

Lets say I want to display products of category 5 and 6 that have features 1 and 2 and tags 3-4-5.

The url for this request should be:

categories/5_6/category5_category6/features/1_2/feature1_feature2/tags/3_4_5/tag3_tag4_tag5/

The important info for this url are the numbers, so even if we misspell some feature description the mvc controller checks only the features ids.

Ideally my controller should receive just the ids.

public ActionResult Find(int[] categories = null, int[] features = null, int[] tags = null)
{

    return View();

}

Is it possible to register routes for this format so it can handle different combinations like

categories/5_6/category5_category6/features/1_2/feature1_feature2 categories/5_6/category5_category6/tags/3_4_5/tag3_tag4_tag5/

...

Thank you

albert
  • 1,493
  • 1
  • 15
  • 33
  • Why not just make this query string parameters? Or better yet a JSON body for a POST request – maccettura Apr 06 '18 at 15:41
  • I would like to be an easy shareable url (no POST) and without query string symbols (= ,& ..). – albert Apr 06 '18 at 15:45
  • A route value of `5_6` cannot possibly bound to an `int[]` - your parameters would need to be `string` and then you would need to convert it to `int[]` using `.Split()` in the controller. And you cannot omit the parameters for the 'names' from the method –  Apr 06 '18 at 22:19
  • And then you would need different route definitions and methods if you wanted to have just 'features' but no 'tags' and vice versa –  Apr 06 '18 at 22:21
  • Look at [Multiple levels in MVC custom routing](https://stackoverflow.com/a/31958586). By subclassing `RouteBase` you can literally program routes to do whatever you want. You just need to 1) determine whether the route matches the request 2) return null if it does not, an object if it does 3) implement `GetVirtualPath` to build the URL based on the route values that are passed (the match/return object or null logic works the same way) - this enables you to use the built-in HTML helpers to generate URLs. Of course, its easier to map a URL to a primary key of the DB and be done with it. – NightOwl888 Apr 08 '18 at 19:09

0 Answers0