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.