Reputation: 20445
I'm having trouble getting model binding to work in the newish ASP.NET Web API.
I'm using jQuery to make my posts, and the client-side JavaScript looks like so:
function postJsonSettings() {
return {
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
xhrFields: {
withCredentials: true
}
};
}
function createCustomer(customer) {
var settings = postJsonSettings();
settings.data = JSON.stringify({ model: customer });
return $.ajax(Payboard.Util.getAbsoluteUrl('/api/customers'), settings);
}
The request that results looks like this:
POST /api/customers HTTP/1.1
Host: dev.payboard.com
Connection: keep-alive
Content-Length: 89
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://www.payboardapitest.com
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://www.payboardapitest.com/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
With a POST payload like this:
{"model":{"ExternalCustomerId":"6c5015c8-d04e-4309-a493-ec0355d1b3a0","Name":"asdfasdf"}}
The C# Web API method that gets called looks like so:
// POST api/customers
public void Post([FromBody] CreateCustomerModel model)
{
// Do stuff
}
With a CreateCustomerModel that looks like this:
public class CreateCustomerModel
{
[Required]
public string ExternalCustomerId { get; set; }
[Required]
public string Name { get; set; }
}
The CustomerController.Post()
method gets called, and the model
itself isn't null, but the ExternalCustomerId
and Name
properties are.
Is there something obvious that I'm doing wrong?
Upvotes: 1
Views: 1075
Reputation: 10175
Trying removing the 'model' in your JSON payload and just send the values for your CreateCustomerModel object. I.e.
{"ExternalCustomerId":"6c5015c8-d04e-4309-a493-ec0355d1b3a0","Name":"asdfasdf"}
Upvotes: 3