Martijn Vaandering
Martijn Vaandering

Reputation: 103

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

Upvotes: 10

Views: 13938

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 22

Nick
Nick

Reputation: 6588

The bla parameter might need to be tagged with [ModelBinder] on your Post method:

[HttpPost]
public string Bla([ModelBinder]Bla bla)
{
    return "bla";
}

Upvotes: 0

Joshua
Joshua

Reputation: 4139

Can you try changing this line:

data: {Bla : bla},

To this:

data: bla,

Upvotes: -1

Related Questions