我正在尝试创建一个表单,将 FormData 对象发送到 API 控制器,将数据序列化到 Article 类,但我无法让它工作。我已经尝试过评论的内容。
这是我的 HTML:
<form onsubmit="postArticle()">
<input type="type" name="Title" value="" />
<input type="type" name="Content" value="" />
<input type="submit" value="Submit" />
</form>
这是我的 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>
控制器:
// 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();
}
和我的文章类:
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}