jQuery AJAX 发布到 MVC 控制器对象——请求显示为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17769008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:55:33  来源:igfitidea点击:

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

javascriptasp.net-mvcjqueryasp.net-mvc-4

提问by SeanKilleen

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

Fiddler:我的请求是什么样的

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

代码:WebAPI 控制器

    [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

代码:页面上的 JavaScript

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

    });


}

回答by Darin Dimitrov

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()
});