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

后端 未结 4 856
深忆病人
深忆病人 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:41

    I use an IBuilder interface and implement it using the ValueInjecter

    public interface IBuilder
    {
          TEntity BuildEntity(TViewModel viewModel);
          TViewModel BuildViewModel(TEntity entity);
          TViewModel RebuildViewModel(TViewModel viewModel); 
    }
    

    ... (implementation) RebuildViewModel just calls BuildViewModel(BuilEntity(viewModel))

    [HttpPost]
    public ActionResult Update(ViewModel model)
    {
       if(!ModelState.IsValid)
        {
           return View(builder.RebuildViewModel(model);
        }
    
       service.SaveOrUpdate(builder.BuildEntity(model));
       return RedirectToAction("Index");
    }
    

    btw I don't write ViewModel I write Input cuz it's much shorter, but that just not really important
    hope it helps

    Update: I'm using this approach now in the ProDinner ASP.net MVC Demo App, it's called IMapper now, there's also a pdf provided where this approach is explained in detail

提交回复
热议问题