[英]why is my ajax request sending a null object to the server
我試圖使用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; }
}
嘗試參數FromBody
屬性:
[HttpPost]
public IActionResult SendEmail([FromBody] Enquiry emailEnquiry)
{
return Json("worked");
}
嘗試跟隨
xhr.send(JSON.stringify(this.data));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.