Spooks
Spooks

Reputation: 7187

Routing, matching a specific url if it contains a word

right now I have a map route that matches

foreach(var subcat in Sports.Categories)
{
routes.MapRoute("MultiRoute" + i, subcat+"/{title}", 
new { controller = "Routing", action = "Redirect", category = subcat });
}

I have some sports categories: Baseball, Soccer, Basketball etc. but I also want to match Basketball with BasketBall-Plays, BasketBall-Highlights, Top-10-Basketball etc...

Which means I have to allow subcat to have a wildcard before and after, as BasketBall-Plays contains the word Basketball, I want it to redirect there.

How can I do a contains section for map routing?

Edit: TLDR: I have a subcat named basketball, but I want to match every url that has the word basketball in it. So Basketball-plays/top-10 should actually hit basketball/top-10

tried:

foreach(var subcat in Sports.Categories)
    {
    routes.MapRoute("MultiRoute" + i, subcat+"/{title}", 
    new { controller = "Routing", action = "Redirect", category = subcat }),
new{sub = ".*"+sub+".*" });
    }

Upvotes: 3

Views: 989

Answers (1)

shakib
shakib

Reputation: 5469

If i understood correctly, the following should work,

var subCategories = new[] { "Soccer", "BasketBall", "Golf" };
foreach (var subcat in subCategories)
{
    routes.MapRoute(subcat, "{subcat}/{title}",
                        new {controller = "Routing", action = "Redirect", category = subcat},
                        new { subcat = @".*\b" + subcat + @"\b.*" });
}

It will route

  • Basketball/top-10
  • Basketball-plays/top-10
  • Basketball plays/top-10
  • Top-10-Basketball/sometitle

hope this helps.

Upvotes: 5

Related Questions