我正在尝试使用 XMLHttpRequest 发出 ajax 请求......当 processRequest 方法被调用时,我的 MVC 操作被命中,但是对象属性值都是空的。
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");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句