views:

526

answers:

2

Given a url that follows the following pattern:

firstcolor={value1}/secondcolor={value2}

where value1 and value2 can vary and an action method like:

ProcessColors(string color1, string color2) in say a controller called ColorController.

I want the following route evaluation:

URL '/firstcolor=red' results in a call like ProcessColors("red", null)
URL '/secondcolor=blue'results in a call like ProcessColors(null, "blue")
URL 'firstcolor=red/secondcolor=blue' ends up in a call like ProcessColors("red", "blue")

Now from I think this can be achieved with a few routes, something like this

route.MapRoute(null,
"firstcolor={color1}/secondcolor={color2}", 
new { controller=ColorController, action = ProcessColors })

route.MapRoute(null,
"firstcolor={color1}}", 
new { controller=ColorController, action = ProcessColors, color2 = (string)null })

route.MapRoute(null,
"secondcolor={color2}}", 
new { controller=ColorController, action = ProcessColors, color1 = (string)null })

This is sufficient for just 2 colors, but as far as I can tell we'll end up with a proliferation of routes if we wanted to have, say 4 colors and be able to have URL's like this:

'/firstcolor=blue/secondcolor=red/thirdcolor=green/fourthcolor=black'
'/firstcolor=blue/thirdcolour=red'
'/thirdcolour=red/fourthcolour=black'

and so on, i.e. we need to cater for any combination given that firstcolor will always be before 2nd, 2nd will always be before 3rd and so on.

Ignoring my ridiculous example, is there any nice way to deal with this sort of situation that doesn't involve lots of routes and action methods needing to be created?

+1  A: 

First of all, if you are going to use that key=value format, then I suggest using QueryString instead of the URL.

But if not, you can do this :

//register this route
routes.MapRoute("color", "colors/processcolors/{*q}",
    new { controller = "Color", action ="ProcessColors" });

Then in your ColorController :

public ActionResult ProcessColors(string q) {
    string[] colors = GetColors(q);
    return View();
}

private string[] GetColors(string q) {
    if (String.IsNullOrEmpty(q)) {
        return null;
    }
    return q.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}

In this case your URLs will be like this :

site.com/colors/processcolors/red
site.com/colors/processcolors/red/green
çağdaş
A: 

In the case that we use the wildcard mapping I suppose we lose the ability to use Html.ActionLink to build our URL's for us?

vakman
You'd have to build your own ActionLink extension, e.g. ActionLinkForColors("red", "blue", "green", "orange" ...)
ewwwyn