我正在疯狂地尝试找出如何序列化它(在 MVC 3 中):
//1.我在 View 中加载产品数组:
var products = [];
if (quantity > 0) {
products.push({ 'id': id, 'quantity': quantity });
}
//2. 然后我发布一堆值以及产品,如下所示:
$.ajax({
type: "POST",
url: '/Orders/Create/',
data:
{
'ShipToPersonId': shipToPersonId,
'ShipToPersonType': selectedPersonType,
'ShippingAddressId': shipToAddressId,
'ShippingInstructions': 'Not yet implemented',
'LineItems': products,
'OrderOwnerId': selectedOnBehalfOfPersonId
},
dataType: "json",
success: function (data) {
alert('Saved: ' + data);
},
error: function (data) {
alert('failed:' + data);
}
});
//3.我的 Controller 如下所示:
public JsonResult Create(
int ShipToPersonId,
string ShipToPersonType,
int ShippingAddressId,
string ShippingInstructions,
List<LineItem> LineItems,
int OrderOwnerId)
{...}
//4. LineItem 类:
public class LineItem{
public string id {get;set;}
public string quantity { get; set; }
}
在 Controller 函数中,除 LineItem 列表外,所有值均正确传递;它具有正确的元素计数,但 id 和数量值为空。
我已经通过 Fiddler 调用了电话,这就是我得到的:
[Fiddler WebForms View ]
=================================
Body | Value
========================|========
LineItems[0][id] | 50
LineItems[0][quantity] | 10
LineItems[1][id] | 46
LineItems[1][quantity] | 20
LineItems[2][id] | 48
LineItems[2][quantity] | 30
LineItems[3][id] | 30
LineItems[3][quantity] | 50
[Fiddler 查询字符串 View ]
ShipToPersonId=533
&ShipToPersonType=Rep
&ShippingAddressId=517
&ShippingInstructions=Not+yet+implemented
&LineItems%5B0%5D%5Bid%5D=50&LineItems%5B0%5D%5Bquantity%5D=10
&LineItems%5B1%5D%5Bid%5D=46&LineItems%5B1%5D%5Bquantity%5D=20
&LineItems%5B2%5D%5Bid%5D=48&LineItems%5B2%5D%5Bquantity%5D=30
&LineItems%5B3%5D%5Bid%5D=30&LineItems%5B3%5D%5Bquantity%5D=50
&OrderOwnerId=533
显然,序列化字符串和 Controller 参数不“兼容”。我是否没有在 View 中正确格式化产品数组,或者 Controller 中的行项目列表和类不正确,或者两者都不正确?
有人可以解释一下吗?谢谢!
有人关注这个吗?
最佳答案
Here是你的答案。看起来您要么需要在操作之上使用一个属性,要么使用一个插件将您的 json 序列化为默认模型绑定(bind)程序可以理解的内容。
另外,当您在 ajax 请求中将其设置为数据时,您是否在对象上尝试过 JSON.stringify({'foo', 'bar'}) ?
关于jquery - 如何序列化 JSON Post 的 jQuery 对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6845398/