jQuery AJAX post to MVC Controller object -- request shows up null

asp.net-mvc, asp.net-mvc-4, javascript, jquery

Solution

When you JSON.stringifyied your data object you converted it to JSON. But you forgot to set the Content-Type request header and the Web API has no way of knowing whether you are sending JSON, XML or something else:

$.ajax({
    url: '/api/contactus/newmessage',
    type: 'POST',
    contentType: 'application/json',
    done: submissionSucceeded,
    fail: submissionFailed,
    data: dataObject
});

Also when building the JSON you don't need to wrap it in an additional property that matches your method argument name. The following should work as well:

var dataObject = JSON.stringify({
    'Email': $('#inpEmail').val(),
    'Name': $('#inpName').val(),
    'PhoneNumber': $('#inpPhone').val(),
    'Message': $('#inpMessage').val()
});

Problem

I know I'm missing something in the details here. Problem Despite Googling, trying examples, different formats, etc, the AJAX request that I send always is validated as having all fields empty, but not being null. I think I'm not sending things in the proper format for the controller to recognize it as an object but I'm not sure what. Fiddler: What my request looks like With some dummy data: Code: Model Class ``` public class ContactUsMessage { public string Email { get; set; } public string Name { get; set; } public string PhoneNumber { get; set; } public string Message { get; set; } } ``` Code: WebAPI Controller ``` [HttpPost] public HttpResponseMessage NewMessage(ContactUsMessage messageToSend) { if (messageToSend == null) { var sadResponse = Request.CreateResponse(HttpStatusCode.BadRequest, "Empty Request"); return sadResponse; } var messageValidator = new ContactUsMessageValidator(); var results = messageValidator.Validate(messageToSend); var failures = results.Errors; var sadString = ""; if (!results.IsValid) { foreach (var error in failures) { sadString += " Problem: " + error.ErrorMessage; } var sadResponse = Request.CreateResponse(HttpStatusCode.NotAcceptable, "Model is invalid." + sadString); return sadResponse; } else { SendContactFormEmail(messageToSend.Email, messageToSend.Name, messageToSend.PhoneNumber, messageToSend.Message); } ``` Code: JavaScript on Page ``` function sendSubmissionForm() { var dataObject = JSON.stringify( { messageToSend: { 'Email': $('#inpEmail').val(), 'Name': $('#inpName').val(), 'PhoneNumber': $('#inpPhone').val(), 'Message': $('#inpMessage').val() } }); $.ajax({ url: '/api/contactus/newmessage', type: 'POST', done: submissionSucceeded, fail: submissionFailed, data: dataObject }); } ```

Original source