Reputation: 443
I have 2 classes that are used to mirror the data from an ajax call. One (Customer) contains a property which is 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 the 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 while still having a length of 2.
Am I missing something really important here?
Upvotes: 3
Views: 1612
Reputation: 630359
Right now you're not passing JSON, you're passing the data as it is, (serialized with $.param()
)...which 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 stringify it, like this:
data: JSON.stringify({ "Name": this.Name,
"Products": [{ "ProductCode": "product 1", "ProductName": "product 1" },
{ "ProductCode": "product 2", "ProductName": "product 2"}]
}),
Which looks like this:
{"Name":"something","Products":[{"ProductCode":"product 1","ProductName":"product 1"},{"ProductCode":"product 2","ProductName":"product 2"}]}
Now that's something your model can turn back into an object. For older browsers (< IE8) which don't support native JSON
, include json2.js
which will emulate the behavior.
Upvotes: 4