0

在我看来,我通过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]没有奏效是因为我序列化表单的方式,但我不确定。

4

1 回答 1

0

[FromForm]和之间的区别[FromBody]如下:

[FromForm]:从发布的表单字段中获取值。
[FromBody]:从请求正文中获取值。

要使用该[FromBody]属性,您可以通过 JQuery 获取输入的值,然后创建 JavaScript 对象,并将其发送到控制器方法,代码如下:

<script>
    function SaveData() {
        event.preventDefault();
        //var formData = $("#formid").serialize();

        var bookvm = {};
        var book = {};
        book.Title = "hello"; //use jquery to get the entered value 
        book.GenreId = "1001";
        var genre = {};
        genre.Id = 1001;
        genre.Name = "Type A";
        book.Genre = genre;
        bookvm.Book = book;

        $.ajax({
            url: "/Home/BookIndex",  //change the url to yours
            type: "POST",
            data: JSON.stringify(bookvm),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function (request) {
                request.setRequestHeader(
                    "RequestVerificationToken",
                    $("[name='__RequestVerificationToken']").val());
            }
        });
    }
</script>

结果如下:

在此处输入图像描述

于 2020-12-14T06:25:38.060 回答