【发布时间】:2019-10-08 13:25:51
【问题描述】:
我有一个带有此操作的 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 Tâche à 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 tâche à 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 tâche à l'API
const req = new XMLHttpRequest();
req.onload = function () {
...
};
req.open('POST', uri, true);
req.setRequestHeader("Content-Type", "application/json");
req.send(data);
}
表单的每个字段都有一个正确的名称,已启用并包含有效的输入。
但我总是得到“400 : bad request”响应。
Firefox 的调试工具在 XHR 结果中显示以下错误:
输入字符串 '-----------------18691991225667' 不是有效数字。路径 '',第 1 行,位置 43。
title : 出现一个或多个验证错误
我在发送 xhr 之前添加了这段代码以查看数据对象的内容:
let formData = new FormData(document.getElementById("formEdit"));
for (let pair of formData.entries()) {
console.log(pair[0] + ': ' + pair[1] + ", " + typeof pair[1]);
}
结果如下:
idTache: 11
dateCreation: 2019-10-08
dateEcheance: 2019-10-22
priorite: 1
terminee: on
description: essai
这似乎是正确的。那么我使用 FormData 有什么问题呢?
【问题讨论】:
-
您登录
uri和data以确认他们是您认为的那样吗? -
是的,uri 是正确的,数据日志显示在我的帖子末尾
标签: javascript xmlhttprequest asp.net-core-webapi form-data