【问题标题】:How do I Serialize a jQuery Object Array for JSON Post?如何为 JSON Post 序列化 jQuery 对象数组?
【发布时间】:2011-10-14 07:05:38
【问题描述】:

我很想弄清楚如何序列化它(在 MVC 3 中):

// 1.我在View中加载products数组:

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. 我的控制器是这样的:

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

在控制器函数中,所有值都正确传递,除了 LineItem 列表;它具有正确的元素计数,但是 id 和数量值为空。

我已经通过 Fiddler 拨打了电话,这就是我得到的:

[Fiddler WebForms 视图]

=================================
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

[提琴手查询字符串视图]

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

显然,序列化字符串和控制器参数不“兼容”。我是在视图中没有正确格式化产品数组,还是控制器中的 Line Items 列表和类不正确,或者两者兼而有之??

任何人都可以对此有所了解吗?谢谢!

有人知道吗?

【问题讨论】:

    标签: jquery arrays model-view-controller serialization object


    【解决方案1】:

    Here 是您的答案。看起来您要么需要在操作之上使用属性,要么使用插件将您的 json 序列化为默认模型绑定器可以理解的内容。

    另外,当您将对象设置为 ajax 请求中的数据时,您是否尝试过 JSON.stringify({'foo', 'bar'})?

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 2014-03-05
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多