asp.net-mvc - 用于未知数量可选参数的 MVC 处理程序

标签 asp.net-mvc url-routing asp.net-mvc-routing actionresult

我正在开发一个 MVC 路由,该路由将在 URL 末尾采用未知数量的参数。像这样的事情:

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

这些关键字是我们必须匹配的过滤器的值。

到目前为止我能想到的唯一方法是丑陋的......只需创建一个 ActionResult ,它的参数比我可能需要的要多:

ActionResult CategoryPage(字符串 urlValue1、字符串 urlValue2、字符串 urlValue3 等...) { }

这感觉不太对劲。我想我可以将它们塞进查询字符串中,但随后我会丢失我性感的 MVC URL,对吧?有没有更好的方法来声明处理程序方法,以便它处理未知数量的可选参数?

必须在应用程序启动时连接路由,这应该不难。关键字的最大数量可以很容易地从数据库中确定,所以没什么大不了的。

谢谢!

最佳答案

您可以使用如下所示的包罗万象的参数:

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

然后您的搜索操作方法中将有一个参数:

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

以下是包含关键字参数值的可能 URL 的列表:

http://www.example.com/category (关键字:“”)
http://www.example.com/category/foo (关键字:“foo”)
http://www.example.com/category/foo/bar (关键字:“foo/bar”)
http://www.example.com/category/foo/bar/zap (关键字:“foo/bar/zap”)

关于asp.net-mvc - 用于未知数量可选参数的 MVC 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3371615/

相关文章:

c# - 错误: Cannot convert lambda expression to type 'bool' because it is not a delegate type in Kendo Chart

url-routing - 如果值已编码正斜杠,NancyFx 路线似乎已损坏

未读取 C# MVC url 参数

asp.net-mvc - 使用 MSBuild 枚举文件夹

c# - ASP.NET MVC 每个 View 1 个 ViewModel?

ruby-on-rails - 有没有一种铁路方式来获取当前路线的范围?

asp.net-mvc - 未找到与名为 'User' 的 Controller 匹配的类型

asp.net-mvc - 我可以避免这种永久重定向来修复或添加 slug 吗?

c# - 在表中显示记录

javascript - Durandal 路由不起作用——我是否缺少配置设置?