在我看来,我通过BookViewModel
了,我有一个我正在尝试创建的表单Book
。如果我使用该[FromForm]
属性,我可以执行此操作,但我试图了解它与[FromBody]
. 这是我的模型:
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public int GenreId { get; set; } //foreign key from Genre
public virtual Genre Genre { get; set; }
}
public class BookViewModel
{
public ICollection<Book> Books { get; set; }
public Book Book { get; set; }
}
这是我的视图和控制器:
[HttpGet]
public IActionResult Index()
{
BookViewModel books = new BookViewModel
{
Books = _context.Books.Include(x => x.Genre).ToList()
}; // _context.Books is my database context and table
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index([FromForm] BookViewModel b) //works without
{ //[FromForm] too
//code to perform tasks
//etc
//return Json(true); The parameters work fine but I would like [FromBody]
}
看法:
<form id="formid" method="post">
<div asp-validation-summary="ModelOnly"></div>
<label>Title</label>
<input asp-for="Book.Title" class="form-control" />
<span asp-validation-for="Book.Title"></span>
<label>Genre</label>
<input asp-for="Book.GenreId" class="form-control" />
<span asp-validation-for="Book.GenreId"></span>
<button type="button" onclick="SaveData()">Submit</button>
</form>
<script>
function SaveData(){
event.preventDefault();
var formData = $("#formid").serialize();
$.ajax({
url: "/",
type: "POST",
data: formData,
beforeSend: function(request){
request.setRequestHeader(
"RequestVerificationToken",
$("[name=__RequestVerificationToken']").val());
}
});
}
</script>
所有这些代码都可以正常工作,但我想[FromBody]
改用。
我已添加contentType: "application/json"
到我的 ajax,并添加[FromBody]
到我的操作方法中,但是当我提交表单时,BookViewModel
操作方法中为空。我想知道如何使用[FromBody]
withcontentType: "application/json"
而不是提交我的表单application/x-www-url-formencoded
?
[FromBody]
将执行我想要的默认模型绑定。我假设原因[FromBody]
没有奏效是因为我序列化表单的方式,但我不确定。