[英]How to send FormData from javascript to ASP.NET Core 2.1 web API using fetch
i'm trying to create a form that sends FormData object to API controller that serializes the data to Article class, but i cannot get it to work. 我正在尝试创建一个表单,该表单将FormData对象发送到API控制器,该控制器将数据序列化为Article类,但是我无法使其正常工作。 I have already tried the things that are commented.
我已经尝试过评论的内容。
this is my HTML: 这是我的HTML:
<form onsubmit="postArticle()">
<input type="type" name="Title" value="" />
<input type="type" name="Content" value="" />
<input type="submit" value="Submit" />
</form>
this is my JS: 这是我的JS:
<script>
var postArticle = () => {
event.preventDefault();
var Article = new FormData(this.event.target);
console.log([...Article]);
fetch('/api/Articles', {
headers: {
'Content-Type': 'multipart/formdata',
//'Content-Type': 'application/json'
},
method: "POST",
body: Article
//body: JSON.stringify(Article)
})
}
</script>
Controller: 控制器:
// POST: api/Articles
[HttpPost]
public async Task<IActionResult> PostArticle(Article article)
{
string name = article.Title;
if (!ModelState.IsValid)
{
return Ok();
}
_context.Article.Add(article);
await _context.SaveChangesAsync();
return Ok();
}
and my Article class: 和我的Article类:
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
Works now! 现在工作! The solution is to not set any content-type headers along with adding the [FromForm], thank you all contributing.
解决方案是在添加[FromForm]的同时不要设置任何内容类型的标题,谢谢大家的贡献。
part of the solution was at this thread 解决方案的一部分就是在这个线程上
these are the changes: 这些是更改:
var postArticle = () => {
event.preventDefault();
var Article = new FormData(this.event.target);
console.log([...Article]);
fetch('/api/Articles', {
method: "POST",
body: Article
})
}
// POST: api/Articles
[HttpPost]
public async Task<IActionResult> PostArticle([FromForm]Article article)
{
string name = article.Title;
if (!ModelState.IsValid)
{
return Ok();
}
//_context.Article.Add(article);
//await _context.SaveChangesAsync();
return Ok(); //CreatedAtAction("GetArticle", new { id = article.Id }, article);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.