Reputation: 5670
My code is like this Model
public class Department
{
public int DepartmentID { get; set; }
public string Name { get; set; }
public bool Status { get; set; } //no appointments when false
public DateTime CreatedDate { get; set; }
public int CreatedUserId
{
get { return ((SystemUser) HttpContext.Current.Session["CurrentUser"]).SystemUserID; }
}
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="DepartmentID,Name,CreatedUser,CreatedDate")] Department department)
{
if (ModelState.IsValid)
{
db.Entry(department).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(department);
}
View (Edit)
@model DiagnosisApp.Models.Department
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.DepartmentID)
@Html.TextBoxFor(model => model.Name, new { @class = "form-control", @placeholder = "Enter Department Name" })
<button type="submit" value="Save" >Save</button>
}
As you can see in view I only want to Update the Name
field , But when I run the code all fields in table are updated.For which columns I have not added value gets updated with null. Can anyone point out what I am doing wrong here?
Upvotes: 2
Views: 3988
Reputation: 1447
I think what you have done wrong is forgot to attach the entity to the context. And of course model object don't have all the properties. So its model binder sending default values for those properties which is not rendered in the UI.
if (ModelState.IsValid)
{
db.Department.Attach(department);
db.Entry(department).Property(x => x.name).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index");
}
Upvotes: 2