【问题标题】:Best way to add "filter" options to MVC action, for new Web API feature of ASP.NET MVC 4为 ASP.NET MVC 4 的新 Web API 功能添加“过滤器”选项到 MVC 操作的最佳方式
【发布时间】:2012-03-04 18:14:54
【问题描述】:

新的 Web API“东西”看起来很棒。我将把我网站的基础重写为 API,但有几个我担心的场景。

有一个看起来像这样的动作是不是一个坏主意:

GetProducts(long memberId, string categories, int minPrice, int maxPrice, ...)

每个变量都是产品可以过滤的东西。如果变量为 null/空,则不会使用它们来构建查询。

或者是否有其他技术可以达到相同的目标?

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    您可以使用视图模型:

    public class FilterViewModel
    {
        public long MemberId { get; set; }
        public string Categories { get; set; }
        public int MinPrice { get; set; }
        public int MaxPrice { get; set; }
        ...
    }
    

    然后:

    public IEnumerable<ProductViewModel> GetProducts(FilterViewModel filter)
    {
        ...    
    }
    

    【讨论】:

    • 我会让 View Model 的原始属性可以为空,例如 code public int?最低价格 { 得到;放; } code,因此使用可选值更容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 2013-11-10
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多