[英]ASP.NET MVC | HOW to update specific column through EF using Ajax
[英]Update specific fields using EF in asp.net MVC
我有一個需要能夠更新數據的應用程序。 有一個名為“ 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> }
您應該將@ Html.HiddenFor標記助手用於您不想編輯的字段。 這樣,視圖會將字段數據發送回控制器中的POST方法。 例如: <input type="hidden" asp-for="TestName1" />
或@Html.HiddenFor(x => x.TestName1)
會將TestName1字段傳遞給控制器中的post方法。
您正在綁定所有模型,並且僅獲得2個元素。
[Bind(Include = "ID,Description1,Description2,TestName1,TestName2,TestName3,TestComp1,TestComp2,TestComp3,TestDesc1,TestDesc2,TestDesc3,FooterAddress,FooterEmail,FooterTel,FooterFax")]
因此,嘗試在沒有“綁定”選項的情況下執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.