Reputation: 135
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);
}
Upvotes: 2
Views: 1219
Reputation: 4456
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);
}
Upvotes: 0
Reputation: 32059
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);
}
Upvotes: 1