在asp.net MVC中使用EF更新特定字段

时间:2018-05-23 08:47:20

标签: c# asp.net-mvc entity-framework

我有一个需要能够更新数据的应用程序。有一个名为“HomePage”的表有多个字段。为了便于使用,我希望用户只更新此表中的2个字段(Description1和Description2)。在尝试实现此目的时,它确实更新了这两个字段,但删除了表中其他字段中的其余数据。请检查以下代码

Controller.cs

 // GET: HomePages/Edit/5
        public ActionResult EditDescription(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            HomePage homePage = db.HomePages.Find(id);
            if (homePage == null)
            {
                return HttpNotFound();
            }
            return View(homePage);
        }

        // POST: HomePages/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditDescription([Bind(Include = "ID,Description1,Description2,TestName1,TestName2,TestName3,TestComp1,TestComp2,TestComp3,TestDesc1,TestDesc2,TestDesc3,FooterAddress,FooterEmail,FooterTel,FooterFax")] HomePage homePage)
        {
            if (ModelState.IsValid)
            {
                db.Entry(homePage).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(homePage);
        }

CSHTML

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

<div class="form-horizontal">

  <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.ID)

  <div class="form-group">
    @Html.LabelFor(model => model.Description1, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
      @Html.TextAreaFor(model => model.Description1, 5, 100, null) @Html.ValidationMessageFor(model => model.Description1, "", new { @class = "text-danger" })
    </div>
  </div>

  <div class="form-group">
    @Html.LabelFor(model => model.Description2, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
      @Html.TextAreaFor(model => model.Description2 , 8, 100, null) @Html.ValidationMessageFor(model => model.Description2, "", new { @class = "text-danger" })
    </div>
  </div>



  <div class="form-group">
    <div class="col-md-offset-2 col-md-10">
      <input type="submit" value="Save" class="btn btn-default" style="color:white;background-color:#ad301c" />
    </div>
  </div>
</div>
}

2 个答案:

答案 0 :(得分:1)

您应该将@ Html.HiddenFor标记帮助器用于您不想编辑的字段。这样,视图会将字段数据发送回控制器中的POST方法。例如:<input type="hidden" asp-for="TestName1" />@Html.HiddenFor(x => x.TestName1)会将TestName1字段传递给控制器​​中的post方法。

答案 1 :(得分:0)

您绑定所有模型并且只获得2个元素。

[Bind(Include = "ID,Description1,Description2,TestName1,TestName2,TestName3,TestComp1,TestComp2,TestComp3,TestDesc1,TestDesc2,TestDesc3,FooterAddress,FooterEmail,FooterTel,FooterFax")]

因此,如果没有Bind选项,请尝试这样做。