Posting JSON to apicontroller

13,832

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.

Share:
13,832
Martijn Vaandering
Author by

Martijn Vaandering

Updated on July 17, 2022

Comments

  • Martijn Vaandering
    Martijn Vaandering almost 2 years

    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 );
        });
    
    
  • Martijn Vaandering
    Martijn Vaandering over 11 years
    also null's in the controller, but the JS looks cleaner; tnx
  • crush
    crush over 9 years
    Now if $.post only had a method of telling it you want to send JSON and not form urlencoded data, everything would be gravy.