簡體   English   中英

將復雜類型的集合與查詢字符串中的其他屬性綁定

[英]Binding a collection of a complex type with other properties from a query string

我正在使用 asp.net core v2.1,我有一個從Controller繼承的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<T>模型描述了使用操作實現分頁所需的所有參數。

ColumnSorts屬性是一個集合,因為可以進行多個連續的列排序。

我讀過查詢字符串中的數組或列表沒有被解析但是如果我理解這一點,我就不能有一個接受所有查詢參數的模型。

為了成功實現分頁的全部功能,需要所有參數。 ColumnSorts不是集合時,這工作正常,與單列排序一致。

有沒有人知道這種情況下使用查詢字符串的解決方法?

你上面描述的問題已經解決了。 另外,即使它不是固定的,你也可以通過[FromQuery(Name="xxx")]繞過它。 請參閱dougbu 的演練

看來您正在使用[ApiController] ,我用2.1.3022.1.402對其進行了測試,它完美無缺。

假設您要查詢MyColoumnFilter ,它將用作PagingControl<T>類中的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. perPage : int為 10
  3. columnFilters : columnFilters.fieldA=1&columnFilters.fieldB=2
  4. columnSorts[] :由於ColumnSorts是一個數組,我們應該構造像columnSorts[0].Field=xx&columnSorts[0].Type=Asc&columnSorts[1].Field=...

作為旁注,如果您使用GET http 方法,它會使查詢字符串變得相當復雜。 請參閱我的另一個答案下的Chris Pratt 評論

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM