为什么我的ajax请求将空对象发送到服务器

时间:2017-08-08 12:30:42

标签: javascript ajax typescript asp.net-core xmlhttprequest

我正在尝试使用XMLHttpRequest创建一个ajax请求...当调用processRequest方法时,我的MVC操作被命中,但是对象属性值都是null。

Ajax类

import {Message} from "./Message";

export class AjaxHelper {

    private url: string;
    private data: Object;
    private callBackFunction: Function;

    constructor(url, data, callback) {
        this.url = url;
        this.data = data;
        this.callBackFunction = callback;
    }

    processRequest(): void {
        //var captcha = grecaptcha.getResponse();
        console.log("from ajax: " + this.data);
        const divOuterNotification = <HTMLDivElement>document.getElementById("divEmailMessage");

        var xhr = new XMLHttpRequest();
        xhr.open("POST", this.url, true);
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status <= 300) {
                this.callBackFunction(divOuterNotification, Message.enquirySent);
            } else {
                this.callBackFunction(divOuterNotification, Message.error);
            }
        }

        xhr.onerror = () => {
            this.callBackFunction(divOuterNotification, Message.error);
        }

        xhr.send(this.data);
    }

}

我如何调用我的ajax请求

var ajaxObj = new AjaxHelper("/Home/SendEmail", emailEnquiry, this.uiHelper.addNotification);
ajaxObj.processRequest();

MVC行动方法

[HttpPost]
public IActionResult SendEmail(Enquiry emailEnquiry)
{
    return Json("worked");
}

下面是我的对象,客户端对象以及它在C#中应该是什么。

JS对象

    var emailEnquiry = {
        SenderName: txtNameVal,
        SenderEmail: txtEmailVal,
        SenderTelephone: txtTelephoneVal,
        SenderEnquiry: txtEnquiryVal,
        CaptchaResponse: ""
    };

C#对象

public class Enquiry
{
    [Required(AllowEmptyStrings = false)]
    public string SenderName { get; set; }
    [Required(AllowEmptyStrings = false)]
    public string SenderEmail { get; set; }
    public string SenderTelephone { get; set; }
    [Required(AllowEmptyStrings = false)]
    public string SenderEnquiry { get; set; }
    public string CaptchaResponse { get; set; }
}

2 个答案:

答案 0 :(得分:1)

尝试参数前面的FromBody属性:

[HttpPost]
public IActionResult SendEmail([FromBody] Enquiry emailEnquiry)
{
    return Json("worked");
}

答案 1 :(得分:0)

尝试以下

xhr.send(JSON.stringify(this.data));