2017-08-08 23 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

我試過這個,似乎沒有工作 –

相關問題