MVC处理器未知数可选参数 [英] MVC Handler for an unknown number of optional parameters

查看:87
本文介绍了MVC处理器未知数可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我workingon,将采取对URL的末尾未知数量的参数的MVC路线。事情是这样的:

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

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

这些关键字是过滤器值,我们一定要配合。

Those keywords are values for filters we have to match.

我目前可以想到的唯一办法是丑陋的...只是使有更多的参数,一个ActionResult比我以往任何时候都可能需要的:

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(字符串urlValue1,串urlValue2,串urlValue3,等...)
{
}

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

这只是感觉不对。我想我可以塞进他们到一个查询字符串,但后来我失去了我的性感MVC的网址,对不对?有没有更好的方式来声明处理程序方法,以便它处理可选参数的UKNOWN多少?

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.

谢谢!

推荐答案

您可以使用一个包罗万象的参数是这样的:

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.
}

下面是可能的URL用关键字参数的值的列表:

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

http://www.example.com/category (关键词:)结果
http://www.example.com/category/foo (关键词:富)结果
http://www.example.com/category/foo/bar (关键词:富/栏)结果
http://www.example.com/category/foo/bar/zap (关键词:富/酒吧/ ZAP)

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

这篇关于MVC处理器未知数可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆