5

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');
    }
});
6
  • Try sending UserID as a number instead of a string.
    – Musa
    Sep 12, 2013 at 17:18
  • 1
    @Archer you have it wrong, content type is what you're sending and data type is what you're expecting.
    – Musa
    Sep 12, 2013 at 17:20
  • Good catch on UserID, but changing it has no effect on the problem.
    – Scott
    Sep 12, 2013 at 17:20
  • The URL is valid, can you use a breakpoint in the action save? Sep 12, 2013 at 17:26
  • Yes, the URL is valid and I can hit breakpoints.
    – Scott
    Sep 12, 2013 at 17:27

1 Answer 1

7

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!

1
  • I get tripped up on this exact issue a lot when using Fiddler for testing - remember to add 'Content-Type: application/json' to your composer headers!
    – profMamba
    Nov 28, 2013 at 2:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.