我必须发布这个对象结构:
public class Parent
{
public List<Child> Childs {get; set;}
}
public class Child
{
public String Name {get; set;}
}
我用 jquery 进行 POST 调用:
var myjson={
"Childs":[{"Name":"Pippo"},{"Name":"Pluto"}]
}
$.ajax({
type: "POST",
url: "/parent",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(myjson),
traditional: true,
success: function (result) {
console.log(result);
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
}
});
这是父控制器:
public class ParentController : ApiController{
[HttpPost]
[ActionName("DefaultAction")]
public HttpResponseMessage Post(Parent obj){
// obj.Childs.Count is 2
// but obj.Childs[0].Name is null
}
}
问题是我收到一个有两个孩子的父对象,但孩子的名字是空的。
更新,我找到了一种解决方法,这种方式似乎有效:
public class ParentController : ApiController{
[HttpPost]
[ActionName("DefaultAction")]
public HttpResponseMessage Post(JObject obj){
Parent p=obj.ToObject<Parent>();
// p.Childs[0].Name is Pippo
}
}