单击编辑后数据未填充到表单中

Data not populating in form upon clicking edit

我正在处理这个 ASP.NET MVC 项目,我正在执行简单的 CRUD 操作。单击 Edit 按钮后,我想从数据库中获取数据并将其填充到 Create 视图中(在我输入数据的帮助下使用相同的视图)。

我遇到的问题是,虽然我可以使用 Create.cshtml 视图将数据输入数据库,但我无法将数据填充回相同的字段 View 单击 Edit。检查时,我发现我能够从 Controller 的数据库中获取数据,并将其发送到 View - Create。但是,View 中没有填充这些字段。

我哪里错了?

查看 - Create.cshtml

<form method="post" action="/Books/Create" id="formBooks">
    <div class="form-group">
        <div class="form-row">
            <div class="form-group col-md-6">
                <div>
                    <label asp-for="Title" class="label">Title</label>
                    <input asp-for="Title" class="form-control" id="title" name="title" required />
                    <span asp-validation-for="Title" class="text-danger"></span>
                </div>
                <div>
                    <label asp-for="Author" class="label">Author</label>
                    <input asp-for="Author" class="form-control" id="author" name="author" required />
                <span asp-validation-for="Author" class="text-danger"></span>
                </div>

                ...

            </div>
            <div class="form-group col-md-6">
                <button type="submit" value="Save" class="btn bgm-orange waves-effect mybtn">SAVE</button>
            </div>
        </div>
    </div>
</form>

控制器 - BooksController.cs

public ActionResult Create(int? Id)
{
    if(Id == null)
    {
        return View();
    }
    else
    {
        var bookData = _context.Books
            .Where(b => b.ID == Id)
            .FirstOrDefault();

        return View(bookData);
    }
}
public ActionResult Create(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Books books= db.Books.Find(id);
        if (books== null)
        {
            return HttpNotFound();
        }
        return View(books);
    }

//尝试一下,希望能奏效

name 属性在将数据绑定到 <input></input> 字段中起着至关重要的作用。此外,value 属性获取要显示在 Edit 视图中的值。

<input asp-for="Title" class="form-control" id="title" name="title" placeholder="Enter title..." value="@(Model != null ? Model.Title : "")" required />