1

And this is the class I'm using. I used the db first approach.

public partial class Ingredient
{
    public int id { get; set; }
    public string name { get; set; }
    public string desc{ get; set; }
    public byte is_deleted { get; set; }
    public int Ingredient_Type_id { get; set; }
    public int UOM_id { get; set; }
}

I have this code, the scaffolded one that updates a record.

public ActionResult EditDetails(Ingredient ingredient)
{           
   if (ModelState.IsValid)
   {
      db.Entry(ingredient).State = EntityState.Modified;
      db.SaveChanges();
      return RedirectToAction("Index");
   }
   ViewBag.UOM_id = new SelectList(db.Unit_Of_Measurement, "id", "name", ingredient.UOM_id);
   ViewBag.Ingredient_Type_id = new SelectList(db.Ingredient_Type, "id", "name", ingredient.Ingredient_Type_id);
   return View(ingredient);
}

From what I see and understand in the code above, it updates all the fields in the record. However, I want to only update the name and desc fields. How should I do this? I'm also new in doing this, so an explanation will be appreciated too. Thank you.

AyakoS
  • 221
  • 2
  • 7
  • 18
  • Your editing data so always use a view model - [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc). In you POST method you get the data model based on the ID, and update only the properties your want from the view model. –  Oct 02 '17 at 21:01

2 Answers2

0

you need a viewmodel, another class that has only the properties you need in the view, and when you get it in the action as parameter you map it to the actual entity something like this:

public class IngredientInput
{
    public int id { get; set; }
    public string name { get; set; }
    public string desc{ get; set; }
}

public ActionResult EditDetails(Ingredient input)
{           
   if (ModelState.IsValid)
   {
      var ent = db.Set<Ingredient>().SingleOrDefault(o => o.id == input.id)
      ent.name = input.name;
      ent.desc = input.desc;
      db.SaveChanges();
      return RedirectToAction("Index");
   }
...
Omu
  • 69,856
  • 92
  • 277
  • 407
0

You can simply avoid updating the other fields. To achieve that you should define the properties you dont want to change under entity state modify declaration. So the answer to your problem would be:

                if (ModelState.IsValid)
            {
                db.Entry(ingredient).State = EntityState.Modified;
                db.Entry(ingredient).Property("is_deleted").IsModified = false;
                db.Entry(ingredient).Property("Ingredient_Type_id").IsModified = false;
                db.Entry(ingredient).Property("UOM_id").IsModified = false;
                db.SaveChanges();
                return RedirectToAction("Index");
            }