Passing complex json jQuery data to action

I have 2 classes that are used to mirror data from an ajax call. One ( Client ) contains a property, which is a name, and the other is an array of Products .

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

and ajax call:

$.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!");
        }
    });

The value for Customer.Name is reflected, but the properties of the Products remain nothing, but still have a length of 2.

Did I miss something really important here?

+3
source share
1 answer

Right now, you are not transmitting JSON, you are transmitting data as it is (serialized $.param()) ... looks like this:

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

To pass JSON, you need to strengthen it, for example:

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"}]}

, . (< IE8), native JSON, json2.js, .

+4

Source: https://habr.com/ru/post/1777862/


All Articles