How to map View Model back to Domain Model in a POST action?

后端 未结 4 831
深忆病人
深忆病人 2020-12-04 04:55

Every article found in the Internet on using ViewModels and utilizing Automapper gives the guidelines of the \"Controller -> View\" direction mapping. You take a domain mod

4条回答
  •  失恋的感觉
    2020-12-04 05:36

    Tools like AutoMapper can be used to update existing object with data from source object. The controller action for updating might look like:

    [HttpPost]
    public ActionResult Update(MyViewModel viewModel)
    {
        MyDataModel dataModel = this.DataRepository.GetMyData(viewModel.Id);
        Mapper(viewModel, dataModel);
        this.Repostitory.SaveMyData(dataModel);
        return View(viewModel);
    }
    

    Apart from what is visible in the snippet above:

    • POST data to view model + validation is done in ModelBinder (could be exended with custom bindings)
    • Error handling (i.e. catching data access exception throws by Repository) can be done by [HandleError] filter

    Controller action is pretty thin and concerns are separated: mapping issues are addressed in AutoMapper configuration, validation is done by ModelBinder and data access by Repository.

提交回复
热议问题