【问题标题】:Data not populating in form upon clicking edit单击编辑时数据未填充到表单中
【发布时间】:2019-08-02 10:51:25
【问题描述】:

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

我遇到的问题是,虽然我能够使用 Create.cshtml 视图将数据输入到数据库中,但我无法在单击 @ 时将数据重新填充到相同的 View 字段中987654327@。检查时,我发现我能够从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);
    }
}

【问题讨论】:

  • 您确定bookData 不为空并且实际上包含数据吗?将 .FirstOrDefault() 更改为 First()
  • 是的。我验证了。它包含所需的数据。

标签: asp.net-mvc model-binding


【解决方案1】:
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);
    }

//试试这个,希望能成功

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-06
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2018-02-27
      • 2022-10-20
      相关资源
      最近更新 更多