ASP.NET MVC - Partially updating model from view

前端 未结 6 720
独厮守ぢ
独厮守ぢ 2021-01-31 20:17

I just wondered how people were approaching this situation. It\'s something that seems like a weak point in my usage of MVC with ORMs (NHibernate in this case)...

Say y

6条回答
  •  野的像风
    2021-01-31 21:10

    Why don't you use TryUpdateModel with the form collection.

    If your view is editing a person

    public class Person
    {
        public string ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
    }
    

    And your view is only editing first name and last name, you can do this:

    public ActionResult Action(FormCollection form)
    {
        Person personToUpdate = Repository.GetPerson(form["ID"]);
    
        TryUpdateModel(personToUpdate, form);
    
        Repository.Update(personToUpdate)
    
        return View();
    }
    

    That will only update Person with the items that a part of the form collection. If you don't want a field updated, don't submit it with the form.

提交回复
热议问题