MVC 6 Bind Attribute disappears?

The best way to prevent overposting is to get the entity, update only the properties needed to update and save it.

Assuming you have a view model like

public class CustomerViewModel
{
   public int Id {set;get;}
   public String UserName {set;get;}
   public String FirstName {set;get;}
   public String LastName {set;get;}

}

And assume there is a view called Update which shows UserName in readonly/display only form and FirstName and LastName in editable fields. So even if user posts an updated UserName via some means, we should not be updating that field value.

[HttpPost]
public ActionResult Update(CustomerViewModel model)
{
  var customer = yourDbContext.Customers.FirstOrDefault(s=>s.Id==model.Id);
  if(customer!=null)
  {
    // Updating only fields which are supposed to be updated from the view.

    customer.FirstName = model.FirstName;
    customer.LastName = model.LastName;

    yourDbContext.Entry(customer).State = EntityState.Modified;
    yourDbContext.SaveChanges();

    return RedirectToAction("UpdatedSuccessfully");
  }
  return View("NotFound");
}

Leave a Comment