Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting JSON to apicontroller

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 );
    });

like image 932
Martijn Vaandering Avatar asked Oct 15 '12 10:10

Martijn Vaandering


1 Answers

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.

like image 57
Darin Dimitrov Avatar answered Nov 09 '22 15:11

Darin Dimitrov