MVC Handler for an unknown number of optional para

2019-05-18 07:45发布

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!

2条回答
祖国的老花朵
2楼-- · 2019-05-18 08:07

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")

查看更多
混吃等死
3楼-- · 2019-05-18 08:13

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.

查看更多
登录 后发表回答