Reputation: 3545
Here's what I'm trying to post to my ServiceStack web service:
$.ajax({
url: 'http://localhost:8092/profiles',
type:'POST',
data: {
FirstName : "John",
LastName : "Doe",
Categories : [ "Category 1", "Category 2", "Category 3" ]
},
success: function (response) { $('#response').append('Success!'); },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' Error: ' + thrownError);
},
dataType: "json"
});
And here's the destination class:
[Route("/profiles", "POST")]
public class ProfileRequest
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
public string[] Categories{ get; set; }
}
All the fields are being populated except for the array. Can ServiceStack just not handle objects of this complexity or am I missing something?
Note: I've seen Unable to deserialize array which suggests using JSON.stringify() but that solution still doesn't seem to work, in fact it makes it worse by causing no data to be deserialized.
Upvotes: 0
Views: 247
Reputation: 21521
ServiceStack can handle this, but your jQuery $.ajax
data has to be JSON stringified using the JSON.stringify()
method and set the contentType
to application/json
otherwise jQuery will try posting the data as application/x-www-form-urlencoded
and deserialising will fail.
So your request should be:
$.ajax({
url: 'http://localhost:8092/profiles',
type:'POST',
data: JSON.stringify({
FirstName: "John",
LastName: "Doe",
Categories: [ "Category 1", "Category 2", "Category 3" ]
}),
success: function (response) { $('#response').append('Success!'); },
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' Error: ' + thrownError);
},
contentType: "application/json",
dataType: "json"
});
Hope that helps.
Upvotes: 3