C# 使用HTTP GET对绑定集合进行建模

C# 使用HTTP GET对绑定集合进行建模,c#,.net,asp.net-core,query-string,asp.net-core-mvc,C#,.net,Asp.net Core,Query String,Asp.net Core Mvc,我想在HTTP中对对象集合进行模型绑定,如下所示: public class Model { public string Argument { get; set; } public string Value { get; set; } } [HttpGet("foo")] public IActionResult GetFoo([FromQuery] IEnumerable<Model> models) { } 变化不大。鉴于此模型和行动方法: public cl

我想在HTTP中对对象集合进行模型绑定,如下所示:

public class Model
{
    public string Argument { get; set; }
    public string Value { get; set; }
}

[HttpGet("foo")]
public IActionResult GetFoo([FromQuery] IEnumerable<Model> models) { }
变化不大。鉴于此模型和行动方法:

public class CollectionViewModel
{
    public string Foo { get; set; }
    public int Bar { get; set; }
}


public IActionResult Collection([FromQuery] IEnumerable<CollectionViewModel> model)
{

    return View(model);
}
请注意,不能混合使用这些语法,因此
?[0]。Foo=Baz&model[1]。Foo=Qux
将只使用第一个模型


默认情况下不支持无索引的重复,因此
?model.Foo=Baz&model.Foo=Qux
不会填充您的模型。如果这就是您所说的“好看”的意思,那么您需要创建一个自定义模型绑定器。

@CodeCaster这是针对ASP.NET Core的。在标记为重复之前,请先查看标记。创建自定义模型活页夹如何?@Muhammad嗯,我想这是一个单独的问题,在这个问题中,您应该解释您希望支持的查询字符串的格式以及您尝试过的内容。更新问题。不要一问两个问题,这会使问题过于宽泛。第一个问题是“集合参数绑定是如何工作的”,这个答案就是答案。如果您想创建一个自定义模型绑定器来支持不同的格式,这是一个不同的问题。再次,阅读并分享你的研究成果。
public class CollectionViewModel
{
    public string Foo { get; set; }
    public int Bar { get; set; }
}


public IActionResult Collection([FromQuery] IEnumerable<CollectionViewModel> model)
{

    return View(model);
}
?[0].Foo=Baz&[0].Bar=42 // omitting the parameter name
?model[0].Foo=Baz&model[0].Bar=42 // including the parameter name