Advanced routing behavior using ASP.NET MVC routing

Given the url following the pattern:

firstcolor = {value1} / {secondcolor = value2}

where value1 and value2 can vary and the action method, for example:

ProcessColors (string color1, string color2), for example, ColorController.

I need the following route estimate:

URL '/ firstcolor = red' results in a call of type ProcessColors ("red", null)
URL '/ secondcolor = blue'results in a call of type ProcessColors (null, "blue")
URL' firstcolor = red / secondcolor = blue 'ends with a call of type ProcessColors ("red", "blue")

Now I think it can be achieved in several ways, 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 only enough for two colors, but as far as I can tell we will get routes propagated if we want, say, 4 colors and have a URL like this:

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

and so on, that is, we need to serve any combination, given that firstcolor will always be before the second, the second will always be before the third, etc.

Ignoring my ludicrous example, is there a good way to handle a situation like this that doesn't require a lot of routes and action methods to be created?

+2


source to share


2 answers


First of all, if you are going to use this format key=value

, I suggest using QueryString instead of URL.

But if not, you can do this:

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

      

Then in 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
+2


source


In the case of using wildcard matching, I suppose we lose the ability to use Html.ActionLink to generate our URL for us?



0


source







All Articles