jQuery AJAX发布到MVC Controller对象 - 请求显示为null

[英]jQuery AJAX post to MVC Controller object — request shows up null


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.

尽管谷歌搜索,尝试示例,不同格式等,我发送的AJAX请求始终被验证为所有字段都为空,但不是空。

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 个解决方案

#1


38  

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:

当您JSON.stringifyied您的数据对象时,您将其转换为JSON。但是您忘记设置Content-Type请求标头,并且Web API无法知道您是要发送JSON,XML还是其他内容:

$.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:

此外,在构建JSON时,您无需将其包装在与方法参数名称匹配的其他属性中。以下应该也可以:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/07/21/888810938a873398119ed07081fd2dc4.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号