MVC2中的查询字符串路由

时间:2010-09-07 16:11:20

标签: asp.net-mvc-2

我正在尝试创建一个到特定控制器/操作的路由,需要接受可选的查询字符串参数。

我想接受的网址是:

/Products/ProductsListJson
/Products/ProductsListJson?productTypeId=1
/Products/ProductsListJson?productTypeId=1&brandId=2
/Products/ProductsListJson?productTypeId=1&brandId=2&year=2010

我有这样的行动:

public JsonResult ProductsListJson(int productTypeId, int brandId, int year)

这样的路线:

routes.MapRoute(
    null, "Products/ProductsListJson",
    new { controller = "Products", action = "ProductsListJson", productTypeId = 0, brandId = 0, year = 0 }
);

我假设操作“ProductsListJson”只是看到查询字符串网址并将它们映射到适当的参数,但这并没有发生。

任何人都知道如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

如果在查询字符串中传递了这些参数,则无需在路径中指定其值:

routes.MapRoute(
    null, "Products/ProductsListJson",
    new { controller = "Products", action = "ProductsListJson" }
);

和你的行动:

public ActionResult ProductsListJson(int? productTypeId, int? brandId, int? year)
{
    ...
}

但是您可能不需要特定的路由,因为默认路由可以正常处理它:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);