【问题标题】:Querystring Route in MVC2MVC2 中的查询字符串路由
【发布时间】:2010-09-07 16:11:20
【问题描述】:

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

我想接受的网址是:

/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”只会看到查询字符串 url 并将它们映射到适当的参数,但这并没有发生。

有人知道如何实现吗?

【问题讨论】:

    标签: asp.net-mvc-2


    【解决方案1】:

    如果这些参数在查询字符串中传递,则无需在路由中指定它们的值:

    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 }
    );
    

    【讨论】:

    • 谢谢。我希望它们自动默认为 0。那可能吗?还是我需要在行动中进行评估?
    • 那么只需使用null coalescing operator。每当您需要使用它们时:productTypeId ?? 0
    • 一切都好..希望路线可以处理..感谢您的帮助:)
    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2016-07-06
    • 2010-11-01
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多