javascript 将ajax中的复杂对象发送到MVC
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30819305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending complex object in ajax to MVC
提问by Saroj
The value of List<Order>
returns as null
in my controller action method while sending the complex object. Can someone help to identify the issue? Do we need to pass array of objects with indexes?
发送复杂对象时List<Order>
返回的值与null
我的控制器操作方法中的一样。有人可以帮助确定问题吗?我们是否需要传递带有索引的对象数组?
JavaScript
JavaScript
function OnCustomerClick() {
//var orders = [];
//orders.push({ 'OrderId': '1', 'OrderBy': 'Saroj' });
var complexObject = {
FirstName: 'Saroj',
LastName: 'K',
//Orders : orders
Orders: [{ OrderId: 1, OrderBy: 'Saroj' }, { OrderId: 2, OrderBy: 'Kumar' }]
};
var obj = { customer: complexObject };
var data2send = JSON.stringify(obj);
$.ajax({
type: "POST",
url: 'Home/TestCustomer1',
data: data2send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) { //call successfull
},
error: function (xhr) {
//error occurred
}
});
};
MVC
MVC
public ActionResult TestCustomer1(Customer customer)
{
return Json(customer);
}
C#
C#
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
List<order> Orders { get; set; }
}
public class order
{
public int OrderId { get; set; }
public string OrderBy { get; set; }
}
回答by Andrew Whitaker
You need to use publicproperties for model binding. Orders
currently has no access modifier, so its private.
您需要使用公共属性进行模型绑定。Orders
当前没有访问修饰符,所以它是私有的。
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<order> Orders { get; set; } // <----
}
Other than that, everything looks fine.
除此之外,一切看起来都很好。