ASP.NET MVC - Partially updating model from view

前端 未结 6 719
独厮守ぢ
独厮守ぢ 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:08

    1. Have your view model map one-to-one with your domain model.

    2. Specify Model as argument for the routeValues as below. This means your view model will be initialized with the values from the domain model. Only the sub set of fields in the form will be overwritten in the resulting personViewData.

    Update View:

    @model ViewModel.PersonView
    
    @using (Html.BeginForm("Update", "Profile", Model, FormMethod.Post))
    {
      ...Put your sub set of the PersonView fields here
    }
    

    ProfileController:

    public ActionResult Update(string userName)
    {
        Person person = _unitOfWork.Person.Get().Where(p => p.UserName == userName).FirstOrDefault();
        PersonView personView = new PersonView();
        Mapper.Map(person, personView);
    
        return View(personView);
    }
    
    [HttpPost]
    public ActionResult Update(PersonView personViewData)
    {
       Person person = _unitOfWork.Person.Get().Where(p => p.UserName == personViewData.UserName).FirstOrDefault();
       Mapper.Map(personViewData, person);
       _unitOfWork.Person.Update(person);
       _unitOfWork.Save();
    
       return Json(new { saved = true, status = "" });
    }
    

提交回复
热议问题