views:

39

answers:

2

I am workingon an MVC route that will take an unknown number of parameters on the end of the URL. Something like this:

domain.com/category/keyword1/keyword2/.../keywordN

Those keywords are values for filters we have to match.

The only approach I can think of so far is UGLY... just make an ActionResult that has more parameters than I am ever likely to need:

ActionResult CategoryPage(string urlValue1, string urlValue2, string urlValue3, etc...) { }

This just doesn't feel right. I suppose I could cram them into a querystring, but then I lose my sexy MVC URLs, right? Is there a better way to declare the handler method so that it handles a uknown number of optional parameters?

The routes will have to be wired up on Application Start, which shouldn't be that hard. The max number of keywords can easily be determined from the database, so no biggie there.

Thanks!

+1  A: 

You could make keywords parts of the same route parameter and concatenate them with dashes (-). Your search route would look like this

routes.MapRoute("Category", "category/{searchstring}", new { controller = "Category", action = "Search", searchstring = "" }, null));

and you would construct your URLs to look like this:

www.domain.com/category/cars-furniture-houses-apparel

You would split it up in your controller action.

Try to avoid huge number of params at all cost.

mare
Thanks! Would love to vote... stackoverflow won't let me let. Yay!
Eric
Wound up basically using this solution, though Kristof Claes' answer was good also. I chose to concatenate with comma ',', but this was essentially what we did.http://www.cpuboards.com/cpu-boards/board-type-mini-itx,cpu-intel-celeron,ethernet-lan-intel-82562,standard-personal-computer/
Eric
+1  A: 

You could use a catch-all parameter like this:

routes.MapRoute("Category", "category/{*keywords}", new { controller = "Category", action = "Search", keywords = "" });

Then you will have one parameter in your Search action method:

public ActionResult Search(string keywords)
{
    // Now you have to split the keywords parameter with '/' as delimiter.
}

Here is a list of possible URL's with the value of the keywords parameter:

http://www.example.com/category (keywords: "")
http://www.example.com/category/foo (keywords: "foo")
http://www.example.com/category/foo/bar (keywords: "foo/bar")
http://www.example.com/category/foo/bar/zap (keywords: "foo/bar/zap")

Kristof Claes
Thanks! Would love to vote... stackoverflow won't let me let. Yay!
Eric