Reputation: 1422
When issuing a PUT or POST command to a WebApi, using explicit content types causes WebAPI serialization to fail. For example, the following ajax call will fail:
$("#updateStudent").click(function (event) {
event.preventDefault();
var json = {
"firstName": $("#firstName").val(),
"middleInitial": $("#middleInitial").val(),
"lastName": $("#lastName").val(),
"birthDate": $("#birthDate").val(),
"gender": $("#gender").val()
};
$.ajax({
url: "api/students/1",
type: "PUT",
accept: "application/json",
contentType: "application/json",
data: json
}
).done(function (data) {
bindStudentDetail(data);
});
});
I can fix the issue by removing the contentType from the ajax options parameter, but I'd be very interested to know why this is happening. I've done a little digging and it looks like the json I'm encoding is being converted back into a form encoded format like this:
firstName=Carlos&middleInitial=R&lastName=Alexander&birthDate=10%2F7%2F1985&gender=Male
Has anyone ran into this and is there any way that I can choose to be explicit about these requests?
Upvotes: 1
Views: 71
Reputation: 27022
I believe you have to actually send a json string (your json
variable is a javascript object, not a json string):
$.ajax({
//...
data: JSON.stringify(json)
})
Upvotes: 1