I'm currently working on an ajax request using XMLHttpRequest, but when the processRequest method is triggered, my MVC action gets hit and all object property values come up as 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 to trigger the 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");
}
Below, you can find the objects - the client object in JavaScript and its equivalent 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; }
}