0

Preface:

I'm working on a project using MVC 5. We've built up our database from which our model is created. Then, we've added the Controllers and Views using Scaffolding. However in the Views we've omitted some of the properties (they should not be shown to the users).
Problem:
In the actions like Edit, as I hit the save button (to update the model) I encounter an exception and I think it requires me to provide the value of all the properties.

Please let me know how can I update just some of the properties (shown in the view)? Please note that I need a solution as general as possible, so as to be able to use it in many Edit actions that I have in this project (Indeed this is the hard part).
Code:
The following are some of the codes that I think are most related to this question:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "AreaCode,Tels,Address")] Area area)
    {//Area has many more properties (defined as required in the database) and I just need to update
        //these : AreaCode,Tels,Address
    if (ModelState.IsValid)
    {
        db.Entry(area).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    ViewBag.Detector = new SelectList(db.Detectors, "DetectorCode", "detectorName", area.Detector);
    ViewBag.Grade = new SelectList(db.Grades, "Gradeid", "GradeName", area.Grade);
    return View(area);
}

SS:

enter image description here

Answers expressed in a simple way are highly appreciated.

AndiGeeky
  • 11,266
  • 6
  • 50
  • 66
Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66

1 Answers1

1

Get your object to update from the database, and sets your model with the old value of properties

public ActionResult Edit([Bind(Include = "AreaCode,Tels,Address")] Area area) {

YourDbContext _db= new YourDbContext();
Area oldArea = _db.Areas.Where(x => x.ID == area.ID).FirstOrDefault();


  // Bind others properties marked with required from database 
   area.x = oldArea.x;
   area.y = oldArea.y;


if (ModelState.IsValid)
{
    db.Entry(area).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
}
ViewBag.Detector = new SelectList(db.Detectors, "DetectorCode", "detectorName", area.Detector);
ViewBag.Grade = new SelectList(db.Grades, "Gradeid", "GradeName", area.Grade);
return View(area);

}