用于未知数量可选参数的 MVC 处理程序
我正在开发一个 MVC 路由,该路由将在 URL 末尾采用未知数量的参数。像这样的:
domain.com/category/keyword1/keyword2/.../keywordN
这些关键字是我们必须匹配的过滤器的值。
到目前为止我能想到的唯一方法是丑陋......只需制作一个 ActionResult ,它的参数比我可能需要的更多:
ActionResult CategoryPage(string urlValue1, string urlValue2, string urlValue3, 等等...) { 这
感觉不太对劲。我想我可以将它们塞进查询字符串中,但随后我会丢失我性感的 MVC URL,对吧?是否有更好的方法来声明处理程序方法,以便它处理未知数量的可选参数?
必须在应用程序启动时连接路由,这应该不难。关键词的最大数量可以很容易地从数据库中确定,所以没什么大不了的。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用如下所示的包罗万象的参数:
然后,您的搜索操作方法中将有一个参数:
以下是可能的 URL 列表以及关键字参数的值:
http://www.example.com/category(关键字:“”)
http://www.example.com/category/foo(关键字:“foo”)< br>
http://www.example.com/category/foo/bar(关键字:“富/酒吧”)
http://www.example.com/category/foo/bar/zap (关键词:“foo/bar/zap”)
You could use a catch-all parameter like this:
Then you will have one parameter in your Search action method:
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")
您可以将关键字作为同一路由参数的一部分,并用破折号 (-) 将它们连接起来。
您的搜索路线将如下所示
,并且您将构建如下所示的 URL:
您将在控制器操作中将其拆分。
不惜一切代价尝试避免大量参数。
You could make keywords parts of the same route parameter and concatenate them with dashes (-).
Your search route would look like this
and you would construct your URLs to look like this:
You would split it up in your controller action.
Try to avoid huge number of params at all cost.