2

I want to update only Status and Country Properties and hence want to prevent Sign Property to be updated on Edit.

Here is my Model class

public class Currency{
        [Required]
        public int Id{ get; set;}
        [Required]
        public string Sign { get; set; }
        [Required]
        public string Country { get; set; }
        [Required]
        public int Status{get;set;}
    }

This is the default Edit method in the controller:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Sign,Country,Status")] Currency currenc)
        {
            if (ModelState.IsValid)
            {
                db.Entry(currenc).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
             return View(currenc);
        }
Luka Kerr
  • 4,161
  • 7
  • 39
  • 50
hamza rafiq
  • 135
  • 2
  • 13

2 Answers2

1

Write the Edit method as follows:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Sign,Country,Status")] Currency currenc)
        {
            if (ModelState.IsValid)
            {
                db.Entry(currenc).State = EntityState.Modified;

                 // Sign Property wouldn't be updated
                db.Entry(currenc).Property(x => x.Sign).IsModified = false;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
             return View(currenc);
        }
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
0

You can load the object from the database, update only the properties that has been changed or you want to change and save it back to the database.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Currency currency)
    {
        if (ModelState.IsValid)
        {
            var record = db.Currencies.Find(currency.Id);
            if(record != null)
              {
                record.Status = currency.Status;
                record.Country = currency.Country;
                db.SaveChanges();
              }


            return RedirectToAction("Index");
        }
         return View(currenc);
    }
Haitham Shaddad
  • 4,336
  • 2
  • 14
  • 19