As I was breaking out some of my MVC controllers to use Web Api I ran into a not so fun error (seen below) when doing a jQuery Post.
I was trying to post a model via jQuery to my Web Api Endpoint and it was failing and it made no sense because when I used Postman via Chrome it would work just fine. My jQuery code is below
var model = {
GroupId: self.SelectedGroup().GroupId,
Name: self.SelectedGroup().Name,
};
$.ajax({
url: route,
type: 'Post',
dataType: "json",
data: model,
success: function(data){
alert("passed");
},
error: function(data) {
alert('There was a (' + data.status + ') returned due to ' + data.statusText + '.'); //or whatever
}
});
My Postman setup looked like
Turns out to find my issue i needed to inspect the error result passed back to jQuery which pointed me towards the real error of
"No MediaTypeFormatter is available to read an object of type 'GroupSelectionModel' from content with media type 'application/x-www-form-urlencoded'."
Now that I knew that jQuery was trying to do a FormUrlEncoded post, not a pure json post I had an idea what the root cause was… ME. I was trying to be clever and only allow for the JsonMediaTypeFormatter and removing ALL other formatters, see below.
What I needed to do was the following
Once I added the correct formatter it all just WORKED.
Till next time,
Posted
12-20-2012 7:06 AM
by
Derik Whittaker