亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 XmlHttpRequest 中的 FormData 將數據發布到

使用 XmlHttpRequest 中的 FormData 將數據發布到

素胚勾勒不出你 2021-11-12 17:48:21
我有一個帶有此操作的 ASP.Net Core Web API:    // POST api/TodoList    [HttpPost]    public void Post([FromBody] Tache tache)    {       TodoListContext.AjouterTache(tache);    }這是 Tache 實體的代碼:    public class Tache    {       public int Id { get; set; }       [DataType(DataType.MultilineText)]       [Required, MaxLength(250)]       public string Description { get; set; }       [DataType(DataType.Date)]       public DateTime DateCreation { get; set; }       [DataType(DataType.Date)]       public DateTime DateEcheance { get; set; }       public int Priorite { get; set; }       public bool Terminee { get; set; }    }我從 javascript SPA 調用操作,使用 XHR 如下:    function ajouterTache() {       // Construit un objet Tache à partir des valeurs saisies       let tache = {};        tache.id = document.getElementById("idTache").value;       tache.dateCreation = document.getElementById("dateCreation").value;       tache.dateEcheance = document.getElementById("dateEcheance").value;       tache.priorite = document.getElementById("priorite").value;       tache.terminee = document.getElementById("terminee").checked;       tache.description = document.getElementById("description").value;        console.log(tache);       // Envoie la tache à l'API       const req = new XMLHttpRequest();       req.onload = function () {          ...       };       req.open('POST', uri, true);       req.setRequestHeader("Content-Type", "application/json");       req.send(JSON.stringify(tache));    }上面的代碼工作正常,但這個沒有:    function ajouterTache() {       data = new FormData(document.getElementById("formEdit"));       // Envoie la tache à l'API       const req = new XMLHttpRequest();       req.onload = function () {        ...       };       req.open('POST', uri, true);       req.setRequestHeader("Content-Type", "application/json");       req.send(data);    }表單的每個字段都有正確的名稱,已啟用并包含有效的輸入。但我總是得到“400:錯誤的請求”響應。Firefox 的調試工具在 XHR 結果中顯示以下錯誤:這似乎是正確的。那么我使用 FormData 有什么問題?
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

如果你想用 發布數據 FormData,那么你不應該設置Content-Type為application/json.Besides,在你的操作參數上使用[FromForm]而不是[FromBody]。


1.在js代碼中刪除以下行


req.setRequestHeader("Content-Type", "application/json");

2.使用【FromForm】


[HttpPost]

 public void Post([FromForm] Tache tache)

結果如下:


idTache:11 dateCreation:2019-10-08 dateEditorial:2019-10-22 優先級:1 已完成:在描述:測試


由于您將數據作為模型 Type 接收Tache,因此您需要傳遞一個名為id而不是idTache顯示在日志結果中的屬性。


您沒有顯示您的視圖代碼,我建議您使用name="id"該輸入文本框。


在我的情況下,正確的日志結果有一個__RequestVerificationToken:,如果您使用它,它也是expeted <form id="formEdit">:


id: 11

dateCreation: 2019-10-08

dateEcheance: 2019-10-22

priorite: 1

terminee: on

description: essai

__RequestVerificationToken:xxxxxxxx


查看完整回答
反對 回復 2021-11-12
  • 1 回答
  • 0 關注
  • 255 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號