【问题标题】:Binding a collection of a complex type with other properties from a query string将复杂类型的集合与查询字符串中的其他属性绑定
【发布时间】:2018-11-09 14:25:47
【问题描述】:

我正在使用 asp.net core v2.1,我有一个从 Controller 继承的控制器,其中包含一个带有基于以下模型的带有 FromQuery 修饰的参数的操作:

public class PagingControl<T>
{
    public ColumnSort[] ColumnSorts { get; set; }

    public T ColumnFilters { get; set; }

    public int Page { get; set; }

    public int PerPage { get; set; }
}

public class ColumnSort
{
    public string Field { get; set; }

    public SortType Type { get; set; }
}

public enum SortType
{
    Asc = 0,
    Desc
}

泛型参数表示具有可为空属性的平面 poco,这些属性提供定义明确的列和值以供过滤。 PagingControl&lt;T&gt; 模型描述了使用操作实现分页所需的所有参数。

ColumnSorts 属性是一个集合,因为可以对多个连续的列进行排序。

我已阅读Array or List in query string does not get parsed,但如果我理解这一点,我将无法拥有一个接受所有查询参数的模型。

为了成功实现分页的全部功能,所有参数都是必需的。当ColumnSorts 不是一个集合时,这工作正常,与单列排序一致。

有人知道这种情况下使用查询字符串的解决方法吗?

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    您上面描述的问题已经修复。此外,即使它不固定,您也可以通过[FromQuery(Name="xxx")] 在它周围走动。见dougbu's walkaround

    看来您使用的是[ApiController],我用2.1.3022.1.402 对其进行了测试,它运行良好。

    假设您要查询MyColoumnFilter,它将在PagingControl&lt;T&gt; 类中用作您的T ColumnFilters

    public class MyColumnFilter
    {
        public string FieldA { get; set; }
        public string FieldB { get; set; }
    }
    

    您在服务器端的操作方法是:

    [Route("api/[controller]")]
    [ApiController]
    public class MyController : Controller
    {
        // GET api/values
        [HttpGet]
        public IActionResult Get([FromQuery]PagingControl<MyColumnFilter> pc)
        { 
            return new JsonResult(pc);
        } 
    
        // ...
    }
    

    如果您发送如下请求:

    GET https://localhost:5001/api/my?page=1&perPage=10&columnFilters.fieldA=1&columnFilters.fieldB=2&columnSorts[0].Field=cs1&columnSorts[0].Type=Asc&columnSorts[1].Field=cs2&columnSorts[1].Type=Desc HTTP/1.1
    

    它将按预期工作:

    查询字符串可以分为4部分:

    1. 页面:int,共 1 个
    2. 每页:int,共 10 个
    3. 列过滤器:columnFilters.fieldA=1&amp;columnFilters.fieldB=2
    4. columnSorts[] :由于ColumnSorts是一个数组,我们应该构造像columnSorts[0].Field=xx&amp;columnSorts[0].Type=Asc&amp;columnSorts[1].Field=...这样的参数

    附带说明,如果您使用GET http 方法,它会使查询字符串相当复杂。请参阅我的另一个答案下的Chris Pratt's comment

    【讨论】:

      猜你喜欢
      • 2017-03-26
      • 1970-01-01
      • 2017-07-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多