Anna Anna - 1 year ago 183
Ajax Question

Web API 2.0 recieve JSON data in camel-case with a pascal-case Model

I am attempting to make a PUT call to my Web API. I have set the following up in the WebApiConfig.cs to handle sending data back to my Web project in camel case.

= new CamelCasePropertyNamesContractResolver();

My data is coming from a row in a Kendo UI Grid. The javascript that makes the Ajax call is below:

save: function(e) {
var dataItem = e.model;
url: apiUrl() + "/roleLocationSecurable",
type: 'PUT',
headers: {
'Authorization': 'Bearer ' + getTwtToken(),
'LocationId': getCurrentLocation()
data: JSON.stringify(dataItem),
dataType: 'json'
//stuff when finished

The data being sent to the Web API looks like this:


The Action on my Web API 2.0 Controller looks like this:

public IHttpActionResult UpdateRoleLocationSecurable(RoleLocationSecurableResource model)
var roleLocationSecurable = Mapper.Map<RoleLocationSecurableResource, RoleLocationSecurable>(model);
return Ok();
return NotFound();

And the Model my controller is expecting has properties named like this:

public int? Id {get;set;}
public int RoleLocationId {get;set;}
public int ModuleId {get;set;}

What's happening is that my Ajax call is firing and the body of my PUT call includes all of the information from above, with the camel case keys. The Web API Controller is being called, but the values in my model are not populated with anything (the model is essentially blank).

The issue I think I have (and maybe I'm wrong) is that the Action on my Web API controller is expecting Pascal Case properties, and my Ajax call is sending Camel Case.

Since the CameCasePropertyNamesContractResolver is handling the serialization of data to camel case, why isn't it handling the deserialization? Is there a simple, easy way to fix this?

Any help on why the above code isn't working would be greatly appreciated.

Answer Source

it looks like you are missing the contentType: "application/json" in your ajax call. In order for Web API to properly handle content negotiation and model binding it has to know what content type is being passed. Without telling the Web API what the content type is it is unable to map the content to the model thus showing it as null on the Action. Below is your snippet updated:

    url: getApiUrl() + "/roleLocationSecurable",
    type: 'PUT',
    headers: {
        'Authorization': 'Bearer ' + getJwtToken(),
        'LocationId': getCurrentLocation()
    data: dataItem,
    dataType: "json",
   **contentType: "application/json"**

I was able to test this and I see a populated model.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download