Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST to WebAPI controller results in null parameters

I'm attempting to POST a JSON string to a WebAPI controller that accepts a complex type as the parameter but all of the parameters properties are always null. Based on the code below, any ideas why? The request is hitting the WebAPI method properly and the parameter is not null, but all of it's properties are.

EDIT: If I remove the call to JSON.stringify(), the parameter properties are populated correctly, but my request body is now a querystring instead of a valid JSON object and this won't fly because my actual object also holds some sub-collections that don't work when passed as a querystring.

Model

public class SavedViewData
{
    public int UserID { get; set; }
    public int? SavedID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

JSON Request Body (copied from Fiddler)

{"UserID":"1","SavedID":null,"Name":"Test","Description":"Description"}

WebAPI Action

[HttpPost]
public int Save(SavedViewData viewData)
{
    return 1;
}

jQuery $.ajax call

var view = {
    UserID: userID,
    SavedID: null,
    Name: 'Test',
    Description: 'Description'
};

$.ajax({
    type: "POST",
    url: '/api/save',
    data: JSON.stringify(view),
    contenttype: "application/json; charset=utf-8",
    success: function (data) {    
        alert('success');
    }
});
like image 520
Scott Avatar asked Sep 12 '13 17:09

Scott


1 Answers

So as I expected, it was something stupid:

contenttype: "application/json; charset=utf-8",

should have been

contentType: "application/json; charset=utf-8",

The "T" in type wasn't capitalized...there goes half a day!

like image 173
Scott Avatar answered Oct 21 '22 06:10

Scott