C#MVC - 传递对象与另一个对象的列表
问题描述:
我想发布一个对象,其中有另一个对象的列表,MVC
接收对象为空。C#MVC - 传递对象与另一个对象的列表
MVC邮政
[HttpPost]
public ActionResult Create(ObjectWithList objectWithList) {
// While debugging objectWithList has its properties null
}
ObjectWithList
public class ObjectWithList
{
public List<Foo> Foo { get; set; }
public AnotherFoo AnotherFoo { get; set; }
}
Foo和AntoherFoo是类与正常属性,如串等
使用邮差我POST: 头:Content-Type as application/json 机构(RAW):
{
"Foo": [
{
"Name": "test"
},
{
"Name": "test"
}
],
"AnotherFoo": {
"Name": "asd",
"Email": "[email protected]"
}
}
如果我只是通过 “富” 空:
{
"Foo": [
{}
]
...
它的工作原理,(充满AnotherFoo)。但只要我尝试在Foo内部传递某些内容,MVC就会将所有内容都设为null。
我正确地命名的JSON
答
Foo和AnotherFoo的性质试着这么做:
var foos = {
"Foo": [
{
"Name": "test"
},
{
"Name": "test"
}
],
"AnotherFoo": {
"Name": "asd",
"Email": "[email protected]"
}
};
$.ajax({
url: "YourUrl",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ objectWithList: foos })
}).done(function(result){
//do something
});
答
您是否尝试过在控制器动作[FromBody]属性?
[HttpPost]
public ActionResult Create([FromBody]ObjectWithList objectWithList) {
}
您是否尝试过在控制器动作** [FromBody] **属性? –
[ASP.NET Core中的模型绑定JSON POST](https://andrewlock.net/model-binding-json-posts-in-asp-net-core/) – aspark