1

I'm trying to POST some data to my web API using jQuery's AJAX function, but MVC doesn't serialise it successfully on the other end - it simply leaves the default values for the model. Some seemingly useful answers don't seem to solve my problem, and its not at all complicated, so I'm not sure what's going wrong.

My model:

public class SavedLevel
{
    public int ID { get; set; }
    public string Data { get; set; }
}

AJAX request:

var postData= {};
postData.ID = 12;
postData.Data = "hello";

$.ajax(
{
    url: "api/level/post",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({data : postData}),
    dataType: "json",
    success: function (data)
    {
        //Something
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        //Something
    }
});

The API controller.

[Route("api/level/post")]
[HttpPost]
public HttpResponseMessage PostLevel(SavedLevel data)
{
    Debug.WriteLine("id : " + data.ID);
    Debug.WriteLine("data : " + data.Data);

    return new HttpResponseMessage(HttpStatusCode.OK);
}

The request body.

{"data":{"ID":12,"Data":"hello"}}

The Debug console outputs 0 and "" instead of the expected 12 and "hello".

Thanks for reading.

Note: I tried using a dynamic object and doesn't work at all - I can't even check if it's null.

Community
  • 1
  • 1
Sean Latham
  • 250
  • 1
  • 12

1 Answers1

1

Change your data to:

data: JSON.stringify(postData),

So the request body becomes:

{"ID":12,"Data":"hello"}

The C# is expecting the SavedLevel object, but you are sending the object wrapped in another object.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • I think the saying "If all you have is a hammer, everything looks like a nail" comes in well here. I guess I was confused by the other solution!! Thanks – Sean Latham Apr 26 '14 at 17:06