MVC 6 Bind Attribute disappears?

前端 未结 1 1904
野性不改
野性不改 2020-11-27 08:47

Pardon me for my noob question but I notice that the bind attribute does not appears as default in controller template anymore for MVC 6.

I know I that the attribute

相关标签:
1条回答
  • 2020-11-27 09:00

    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");
    }
    
    0 讨论(0)
提交回复
热议问题