C#MVC - 传递带有另一个对象列表的对象

时间:2017-06-06 02:58:04

标签: c# asp.net json asp.net-mvc post

我想发布一个包含另一个对象列表的对象,MVC正在接收该对象为null。

MVC Post

[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是具有普通属性的类,如字符串等。

使用Postman I POST: 标题:Content-Type as application / json 身体(原始):

{
    "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "asd@asd.com"
   }
}

如果我只是通过&#34; Foo&#34;空:

{
    "Foo": [
            {}
    ]
    ...

它有效,(填写AnotherFoo)。但是当我尝试在Foo中传递某些内容时,MVC会将所有内容都视为空。

我正确地命名了JSON上的Foo和AnotherFoo的属性

2 个答案:

答案 0 :(得分:1)

您是否尝试过控制器操作的[FromBody]属性?

[HttpPost]
public ActionResult Create([FromBody]ObjectWithList objectWithList) { 

}

答案 1 :(得分:0)

尝试类似:

var foos = {
 "Foo": [
        {
          "Name": "test"
        },
        {
         "Name": "test"
        }
   ],
   "AnotherFoo": {
       "Name": "asd",
       "Email": "asd@asd.com"
   }
};

$.ajax({
    url: "YourUrl",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ objectWithList: foos })
}).done(function(result){
//do something
});