使用 HTTP GET 的模型绑定集合
Model Binding Collection Using HTTP GET
我想像这样在 HTTP GET 中对对象集合进行建模:
public class Model
{
public string Argument { get; set; }
public string Value { get; set; }
}
[HttpGet("foo")]
public IActionResult GetFoo([FromQuery] IEnumerable<Model> models) { }
首先,ASP.NET 核心在这种情况下的默认行为是什么? model binding documentation 是稀疏的,但确实说我可以使用 property_name[index]
语法。
其次,如果默认值不好,我如何通过构建某种我可以重复使用的自定义模型活页夹来获得体面的外观 URL,因为这是一个相当常见的场景。例如,如果我想绑定到以下格式:
?Foo1=Bar1&Foo2=Bar2
以便创建以下对象:
new Model { Argument = "Foo1", Value = "Bar1" }
new Model { Argument = "Foo2", Value = "Bar2" }
变化不大since MVC 5。鉴于此模型和操作方法:
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
请注意,您不能混合使用这些语法,因此 ?[0].Foo=Baz&model[1].Foo=Qux
将仅以第一个模型结束。
默认情况下不支持没有索引的重复,因此 ?model.Foo=Baz&model.Foo=Qux
不会填充您的模型。如果这就是您所说的 "decent looking",那么您将需要创建一个自定义模型活页夹。
我想像这样在 HTTP GET 中对对象集合进行建模:
public class Model
{
public string Argument { get; set; }
public string Value { get; set; }
}
[HttpGet("foo")]
public IActionResult GetFoo([FromQuery] IEnumerable<Model> models) { }
首先,ASP.NET 核心在这种情况下的默认行为是什么? model binding documentation 是稀疏的,但确实说我可以使用 property_name[index]
语法。
其次,如果默认值不好,我如何通过构建某种我可以重复使用的自定义模型活页夹来获得体面的外观 URL,因为这是一个相当常见的场景。例如,如果我想绑定到以下格式:
?Foo1=Bar1&Foo2=Bar2
以便创建以下对象:
new Model { Argument = "Foo1", Value = "Bar1" }
new Model { Argument = "Foo2", Value = "Bar2" }
变化不大since MVC 5。鉴于此模型和操作方法:
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
请注意,您不能混合使用这些语法,因此 ?[0].Foo=Baz&model[1].Foo=Qux
将仅以第一个模型结束。
默认情况下不支持没有索引的重复,因此 ?model.Foo=Baz&model.Foo=Qux
不会填充您的模型。如果这就是您所说的 "decent looking",那么您将需要创建一个自定义模型活页夹。