Reputation: 1359
I can't return javascript object to web method thru ajax call like below:
var person = {"FirstName":"Foo","LastName":"Bar"};
$.ajax({
type: "POST",
url: url,
data: person,
contentType: "application/json; charset=utf-8",
dataType: "json",
onSuccess: function () { alert('Success!'); },
onError: function () { alert('Error'); }
});
Invalid JSON primitive is thrown with the method above. I'd to resort to string manipulation like this:
var person = {"FirstName":"Foo","LastName":"Bar"};
var json = '{person:' + JSON.stringify(person) + '}';
$.ajax({
type: "POST",
url: url,
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
onSuccess: function () { alert('Success!'); },
onError: function () { alert('Error'); }
});
Now, this is working fine, i can get away with this solution, but life is hard, we don't want harder! If there's a way to pass the object directly i'd love to hear it ;)
Upvotes: 1
Views: 759
Reputation: 1359
var json = '{person:' + JSON.stringify(person) + '}';
did the job :)
Upvotes: 0
Reputation: 37526
The reason for that is likely that this:
data: person
Actually sends this:
FirstName=Foo&LastName=Bar
because jQuery breaks down that object into a POST-friendly key/value set. The reason you second version works is because it's actually sending a real JSON string. If you were to do this:
data: JSON.stringify(person)
That would likely work.
Upvotes: 1