Search code examples
javascriptajaxtypescriptasp.net-corexmlhttprequest

why is my ajax request sending a null object to the server


I am attempting to make an ajax request using XMLHttpRequest ... when the processRequest method is called, my MVC action get hit however, the object property values are all null.

Ajax Class

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

}

How i call my ajax request

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

MVC Action method

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

The bellow are my objects, the client object and the equivalent of what it should be in C#.

JS Object

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

C# object

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

Solution

  • Try the FromBody attribute infront of your parameter:

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