在 ASP.NET 核心 MVC 中将复杂模型的形式 Post 转化为控制器
Form Post of an Complex Model to Controller in ASP.NET Core MVC
我有一个关于复杂模型的表格 Post 的问题。我的模型有一个子类和 IEnumerable
s:
public class MyViewModel
{
public int SingleInteger { get; set; }
public IEnumerable<int> MultipleInts { get; set; }
public IEnumerable<MySubclass> AssembledClass { get; set; }
public IEnumerable<string> MultipleStrings { get; set; }
}
public class MySubclass
{
public int Quantity { get; set; }
public int Type{ get; set; }
}
从我的视图获取输入到我的控制器的最佳方式是什么? Modelbinder 甚至可以绑定这个吗?
Can the Modelbinder even bind this?
是的,它可以做比这个 class 结构更复杂的事情。
What is the best way to get the Input from my View to my Controller?
Post 等同于 json.
示例:
你可以POST这个json
{"singleInteger":1,"multipleInts":[1,2,3],"assembledClass":[{"quantity":1,"type":2}],"multipleStrings":["one","two"]}
像这样的控制器方法
public IActionResult Post([FromBody]MyViewModel model)
并且会像这样翻译成 MyViewModel 的实例
var model = new MyViewModel
{
SingleInteger = 1,
MultipleInts = new List<int>(){ 1,2,3 },
AssembledClass = new List<MySubclass>{
new MySubclass
{
Quantity = 1,
Type = 2
}
},
MultipleStrings = new List<string>(){ "one", "two"}
};
我有一个关于复杂模型的表格 Post 的问题。我的模型有一个子类和 IEnumerable
s:
public class MyViewModel
{
public int SingleInteger { get; set; }
public IEnumerable<int> MultipleInts { get; set; }
public IEnumerable<MySubclass> AssembledClass { get; set; }
public IEnumerable<string> MultipleStrings { get; set; }
}
public class MySubclass
{
public int Quantity { get; set; }
public int Type{ get; set; }
}
从我的视图获取输入到我的控制器的最佳方式是什么? Modelbinder 甚至可以绑定这个吗?
Can the Modelbinder even bind this?
是的,它可以做比这个 class 结构更复杂的事情。
What is the best way to get the Input from my View to my Controller?
Post 等同于 json.
示例:
你可以POST这个json
{"singleInteger":1,"multipleInts":[1,2,3],"assembledClass":[{"quantity":1,"type":2}],"multipleStrings":["one","two"]}
像这样的控制器方法
public IActionResult Post([FromBody]MyViewModel model)
并且会像这样翻译成 MyViewModel 的实例
var model = new MyViewModel
{
SingleInteger = 1,
MultipleInts = new List<int>(){ 1,2,3 },
AssembledClass = new List<MySubclass>{
new MySubclass
{
Quantity = 1,
Type = 2
}
},
MultipleStrings = new List<string>(){ "one", "two"}
};