I'm struggling with the "new" WebApi in Asp.Net...
I just want to post some Json but it is not deserializing my data... what am i doing wrong?!
Controller class
public class UtilityController : ApiController
{
[HttpPost]
public string Bla(Bla bla)
{
return "bla";
}
}
Bla Class:
public class Bla
{
public string Een { get; set; }
public string Twee { get; set; }
}
Api config:
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{Action}/{id}", defaults: new { id = RouteParameter.Optional } );
Posted Data:
var bla = $.parseJSON('{"Een":"UNO","Twee":"DUE"}'); $.ajax({ type: "POST", url: "/api/utility/Bla", data: {Bla : bla}, dataType: "json" }).done(function( msg ) { alert( "Data Saved: " + msg ); });
what am i doeing wrong!
You are not sending a JSON request. You are sending an application/x-www-form-urlencoded
request.
So make sure that you are sending a real JSON request:
var bla = { "Een": "UNO", "Twee": "DUE"};
$.ajax({
type: 'POST',
url: '/api/utility/Bla',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(bla),
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Notice how I have set the correct contentType
header to application/json
, how I've used the JSON.stringify
method to send a real JSON request and how I've gotten rid of the useless dataType: 'json'
parameter which jQuery is perfectly capable of automatically deducing from the Content-Type response header that the server sends.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With