MVC Handler for an unknown number of optional parameters

风格不统一 提交于 2019-12-22 10:27:58

问题


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:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3371615/mvc-handler-for-an-unknown-number-of-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!