2017-08-08 88 views
0

我试图让使用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; } 
} 
+0

里面有什么'emailEnquiry'对象? – tchelidze

+0

@tchelidze我已经更新了我与emailEnquire –

回答

1

尝试FromBody属性的参数盈:

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

问题你知道什么'FromBody'属性是用来做什么? – tchelidze

+0

这是用于模型绑定。 json对象应该绑定到请求主体。这是由JSON帖子 – senz

+0

不会发生同样没有'FromBody'属性需要在asp.net核心是什么?仅在x-www-form-urlencoded请求上使用 – tchelidze

0

尝试以下

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

我试过这个,似乎没有工作 –

相关问题