0

I seem to be missing something obvious. I'm using Bind in my edit method to update only the fields listed in Bind. However, all fields are being updated, and becuase many fields aren't included in the form post, those fields are overwritten and set to null. I want to only update the fields listed in Bind.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "customerid,firstname,lastname,businessid,userid")] customers customers)
    {

        if (ModelState.IsValid)
        {
            db.Entry(customers).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
...
    }
tintyethan
  • 1,772
  • 3
  • 20
  • 44

2 Answers2

1

My guess is that you did not include those fields in your form. So when the form is submitted those property values are coming back as null and model binder used the null values on the created(by model binder) customers object. When you save the object, null values will be saved on those properties/fields.

Ideally, what you should be doing is, Read the entity again in your HttpPost action and udpate only those properties you want to udpate.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "CustomerId,FirstName)] 
                                                                          Customers model)
{

    if (ModelState.IsValid)
    {
      var c = db.Customers.FirstOrDefault(s=>s.CustomerId==model.CustomerId);
      if(c!=null)
      {
         c.FirstName = model.FirstName; //update the property value

         db.Entry(c).State = EntityState.Modified;
         await db.SaveChangesAsync();
         return RedirectToAction("Index");
      }
    }

 }

Also, If you prefer, you may consider using a view model (specific to your view) to pass data between your action method and views to update your data as explained in this answer.

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
1

You can select which properties you want to be updated:

if (ModelState.IsValid)
{
    db.Customers.Attach(customers);
    var entry = db.Entry(customers);
    entry.Property(e => e.customerid).IsModified = true;
    entry.Property(e => e.firstname).IsModified = true;
    ...
    await db.SaveChangesAsync();
    return RedirectToAction("Index");
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • thought that was the whole purpose of Bind. Will have to read up on it some more. Thanks. Working with both answers right now. – tintyethan Jan 04 '16 at 16:49
  • 1
    No, the purpose of the Bind attribute is to decide which properties to be bound from the HTTP request. It has strictly nothing to do with Entity Framework. It is purely ASP.NET MVC artifact. – Darin Dimitrov Jan 04 '16 at 16:50
  • Darin Dimitrov! Man you are awesome. Respect! – Moe Jan 04 '16 at 18:53