12

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:

enter image description here

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

    });


}

1 Answer 1

47

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()
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I knew it was something basic I was missing. Thank you for the swift and crisp response!
@Darin Dimitrov i owe you a beer buddy. you are life saver for me

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.