将复杂的JSON数据jQuery传递给Action

时间:2010-12-01 08:13:09

标签: asp.net json asp.net-mvc-2 jquery

我有2个类用于镜像来自ajax调用的数据。一个(客户)包含名称的属性,另一个是产品的数组。

Public Class Customer
    Private _Name as String
    Private _Products as Product()

    Public Property Name() As String
        Get
            Return _Name 
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Public Property Products() As Product()
        Get
            Return _Products
        End Get
        Set(ByVal value As Product())
            _Products= value
        End Set
    End Property

和ajax电话:

$.ajax({
        url: '../../Customer/SaveCustomerData',
        type: "POST",
        dataType: "json",
        data: { "Name": this.Name,
                "Products": [{ "ProductCode": "product 1", "ProductName": "product 1" },
                             { "ProductCode": "product 2", "ProductName": "product 2"}]
        },
        success: function(data) {
            alert("Customer has been saved!");
        }
    });

反映了Customer.Name的值,但产品的属性保持不变,但长度仍为2。

我错过了一些非常重要的东西吗?

1 个答案:

答案 0 :(得分:4)

现在你没有传递JSON,你按原样传递数据,(用$.param()序列化)......看起来像这样:

Name=something&Products%5B0%5D%5BProductCode%5D=product+1&Products%5B0%5D%5BProductName%5D=product+1&Products%5B1%5D%5BProductCode%5D=product+2&Products%5B1%5D%5BProductName%5D=product+2

要传递JSON,您需要对其进行字符串化,如下所示:

data: JSON.stringify({ "Name": this.Name,
        "Products": [{ "ProductCode": "product 1", "ProductName": "product 1" },
                     { "ProductCode": "product 2", "ProductName": "product 2"}]
       }),

看起来像这样:

{"Name":"something","Products":[{"ProductCode":"product 1","ProductName":"product 1"},{"ProductCode":"product 2","ProductName":"product 2"}]}

现在那是你的模型可以变回对象的东西。对于不支持原生JSON的旧浏览器(< IE8),include json2.js将模拟行为。