2017-06-06 121 views
0

我想發佈一個對象,其中有另一個對象的列表,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

+0

您是否嘗試過在控制器動作** [FromBody] **屬性? –

+0

[ASP.NET Core中的模型綁定JSON POST](https://andrewlock.net/model-binding-json-posts-in-asp-net-core/) – aspark

回答

0

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 
}); 
1

您是否嘗試過在控制器動作[FromBody]屬性?

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

} 
相關問題