I have an application that needs to be able to update data. There is a table called "HomePage" with multiple fields. For ease of use, I want the user to update just 2 fields in this table(Description1 and Description2). While trying to achieve this, it does update these 2 fields but the rest of the data in the other fields in the table are deleted. Please check below code
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>
}