asp.net-mvc 如何在 POST 操作中将视图模型映射回域模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2206005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to map View Model back to Domain Model in a POST action?
提问by Anthony Serdyukov
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 model along with all Select Lists into one specialized ViewModel and pass it to the view. That's clear and fine.
The view has a form, and eventually we are in the POST action. Here all the Model Binders come to the scene along with [obviously] anotherView Model which is [obviously] relatedto the original ViewModel at least in the part of naming conventions for the sake of binding and validation.
互联网上关于使用 ViewModels 和利用 Automapper 的每篇文章都给出了“控制器 - > 视图”方向映射的指导方针。您将域模型与所有选择列表一起放入一个专门的 ViewModel 并将其传递给视图。这很清楚也很好。
视图有一个表单,最终我们处于 POST 操作中。在这里,所有模型绑定器都与[显然] 另一个视图模型一起出现,该视图模型[显然]至少在命名约定方面与原始 ViewModel相关,以便绑定和验证。
How do you map it to your Domain Model?
你如何将它映射到你的领域模型?
Let it be an insert action, we could use the same Automapper. But what if it was an update action? We have to retrieve our Domain Entity from the Repository, update it's properties according to the values in the ViewModel and save to the Repository.
让它成为一个插入动作,我们可以使用相同的 Automapper。但是如果它是一个更新操作呢?我们必须从存储库中检索我们的域实体,根据 ViewModel 中的值更新它的属性并保存到存储库。
ADDENDUM 1 (9th of February 2010):Sometimes, assigning Model's properties is not enough. There should be taken some action against Domain Model according to the values of View Model. I.e., some methods should be called on Domain Model. Probably, there should be a kind of an Application Service layer which stands between Controller and Domain in order to process View Models...
附录 1(2010 年 2 月 9 日):有时,分配模型的属性是不够的。应该根据 View Model 的值对 Domain Model 采取一些行动。即,应该在域模型上调用某些方法。也许,应该有一种应用服务层位于控制器和域之间,以便处理视图模型......
How to organize this code and where to place it to achieve the following goals?
如何组织此代码以及将其放置在何处以实现以下目标?
- keep controllers thin
- honor SoC practice
- follow Domain-Driven Design principles
- be DRY
- to be continued ...
- 保持控制器薄
- 荣誉SoC实践
- 遵循领域驱动设计原则
- 干燥
- 未完待续 ...
回答by Omu
I use an IBuilderinterface and implement it using the ValueInjecter
我使用IBuilder接口并使用ValueInjecter实现它
public interface IBuilder<TEntity, TViewModel>
{
TEntity BuildEntity(TViewModel viewModel);
TViewModel BuildViewModel(TEntity entity);
TViewModel RebuildViewModel(TViewModel viewModel);
}
... (implementation) RebuildViewModeljust calls BuildViewModel(BuilEntity(viewModel))
...(实现)RebuildViewModel只是调用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
顺便说一句,我不写 ViewModel 我写 Input 因为它要短得多,但这并不重要
希望它有所帮助
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
更新:我现在在ProDinner ASP.net MVC Demo App 中使用这种方法,它现在被称为 IMapper,还有一个 pdf 提供了详细解释这种方法的地方
回答by PanJanek
Tools like AutoMapper can be used to update existing object with data from source object. The controller action for updating might look like:
AutoMapper 等工具可用于使用源对象中的数据更新现有对象。用于更新的控制器操作可能如下所示:
[HttpPost]
public ActionResult Update(MyViewModel viewModel)
{
MyDataModel dataModel = this.DataRepository.GetMyData(viewModel.Id);
Mapper<MyViewModel, MyDataModel>(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
- POST 数据以查看模型 + 验证在 ModelBinder 中完成(可以使用自定义绑定进行扩展)
- 错误处理(即捕获 Repository 抛出的数据访问异常)可以通过 [HandleError] 过滤器完成
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.
控制器操作非常简单并且关注点是分开的:映射问题在 AutoMapper 配置中得到解决,验证由 ModelBinder 完成,数据访问由 Repository 完成。
回答by Sean Copenhaver
I would like to say that you reuse the term ViewModel for both directions of the client interaction. If you have read enough ASP.NET MVC code in the wild you have probably seen the distinction between a ViewModel and an EditModel. I think that is important.
我想说的是,您将术语 ViewModel 重用于客户端交互的两个方向。如果您已经阅读了足够多的 ASP.NET MVC 代码,您可能已经看到了 ViewModel 和 EditModel 之间的区别。我认为这很重要。
A ViewModel represents all the information required to render a view. This could include data that is rendered in static non-interactive places and also data purely to perform a check to decide on what exactly to render. A Controller GET action is generally responsible for packaging up the ViewModel for its View.
ViewModel 表示呈现视图所需的所有信息。这可能包括在静态非交互式位置呈现的数据,以及纯粹用于执行检查以确定要呈现的内容的数据。控制器 GET 操作通常负责为其视图打包 ViewModel。
An EditModel (or perhaps an ActionModel) represents the data required to perform the action the user wanted to do for that POST. So an EditModel is really trying to describe an action. This will probably exclude some data from the ViewModel and although related I think it's important to realize they are indeed different.
EditModel(或者可能是 ActionModel)表示执行用户想要为该 POST 执行的操作所需的数据。所以一个 EditModel 实际上是在试图描述一个动作。这可能会从 ViewModel 中排除一些数据,尽管相关,但我认为意识到它们确实不同很重要。
One Idea
一个想法
That said you could very easily have an AutoMapper configuration for going from Model -> ViewModel and a different one to go from EditModel -> Model. Then the different Controller actions just need to use AutoMapper. Hell the EditModel could have a functions on it to validate it's properties against the model and to apply those values to the Model itself. It's not doing anything else and you have ModelBinders in MVC to map the Request to the EditModel anyway.
也就是说,您可以很容易地拥有一个 AutoMapper 配置,用于从 Model -> ViewModel 和另一个从 EditModel -> Model 进行的配置。那么不同的 Controller 动作只需要使用 AutoMapper 即可。该 EditModel 可以有一个函数来验证它对模型的属性并将这些值应用于模型本身。它没有做任何其他事情,并且您在 MVC 中有 ModelBinders 来将请求映射到 EditModel。
Another Idea
另一个想法
Beyond that something I have been thinking about recently that sort of works off the idea of an ActionModel is that what the client is posting back to you is actually the description of several actions the user performed and not just one big glob of data. This would certainly require some Javascript on the client side to manage but the idea is intriguing I think.
除此之外,我最近一直在思考,基于 ActionModel 的想法是,客户端发回给您的实际上是对用户执行的几个操作的描述,而不仅仅是一大堆数据。这当然需要客户端的一些 Javascript 来管理,但我认为这个想法很有趣。
Essentially as the user performs actions on the screen you have presented them, Javascript would start create a list of action objects. An example is possibly the user is at an employee information screen. They update the last name and add a new address because the employee has recently been married. Under the covers this produces a ChangeEmployeeNameand an AddEmployeeMailingAddressobjects to a list. The user clicks 'Save' to commit the changes and you submit the list of two objects, each containing just the information needed to perform each action.
本质上,当用户在您呈现给他们的屏幕上执行操作时,Javascript 将开始创建一个操作对象列表。一个例子是用户可能在员工信息屏幕上。他们更新姓氏并添加新地址,因为该员工最近刚结婚。在幕后,这会生成一个ChangeEmployeeName和AddEmployeeMailingAddress一个列表的对象。用户单击“保存”以提交更改,然后您提交两个对象的列表,每个对象仅包含执行每个操作所需的信息。
You would need a more intelligent ModelBinder then the default one but good JSON serializer should be able to take care of the mapping of the client side action objects to the server side ones. The server side ones (if you are in a 2-tier environment) could easily have methods that completed the action on the Model they work with. So the Controller action ends up just getting an Id for the Model instance to pull and a list of actions to perform on it. Or the actions have the id in them to keep them very separate.
您需要一个更智能的 ModelBinder,然后是默认的但好的 JSON 序列化程序应该能够处理客户端操作对象到服务器端操作对象的映射。服务器端的(如果您处于 2 层环境中)可以轻松拥有完成对它们使用的模型的操作的方法。因此,Controller 操作最终只会获取要拉取的 Model 实例的 Id 以及要对其执行的操作列表。或者动作中有 id 以保持它们非常独立。
So maybe something like this gets realized on the server side:
所以也许像这样的事情会在服务器端实现:
public interface IUserAction<TModel>
{
long ModelId { get; set; }
IEnumerable<string> Validate(TModel model);
void Complete(TModel model);
}
[Transaction] //just assuming some sort of 2-tier with transactions handled by filter
public ActionResult Save(IEnumerable<IUserAction<Employee>> actions)
{
var errors = new List<string>();
foreach( var action in actions )
{
// relying on ORM's identity map to prevent multiple database hits
var employee = _employeeRepository.Get(action.ModelId);
errors.AddRange(action.Validate(employee));
}
// handle error cases possibly rendering view with them
foreach( var action in editModel.UserActions )
{
var employee = _employeeRepository.Get(action.ModelId);
action.Complete(employee);
// against relying on ORMs ability to properly generate SQL and batch changes
_employeeRepository.Update(employee);
}
// render the success view
}
That really makes the posting back action fairly generic since you are relying on your ModelBinder to get you the correct IUserAction instance and your IUserAction instance to either perform the correct logic itself or (more likely) call into the Model with the info.
这确实使回发操作变得相当通用,因为您依赖 ModelBinder 为您提供正确的 IUserAction 实例和您的 IUserAction 实例来执行正确的逻辑本身或(更有可能)使用信息调用模型。
If you were in a 3 tier environment the IUserAction could just be made simple DTOs to be shot across the boundary and performed in a similar method on the app layer. Depending on how you do that layer it could be split up very easily and still remain in a transaction (what comes to mind is Agatha's request/response and taking advantage of DI and NHibernate's identity map).
如果您处于 3 层环境中,则 IUserAction 可以只是简单的 DTO,以便跨边界拍摄并在应用程序层以类似的方法执行。根据您如何执行该层,它可以很容易地拆分并仍然保留在事务中(想到的是 Agatha 的请求/响应并利用 DI 和 NHibernate 的身份映射)。
Anyway I'm sure it's not a perfect idea, it would require some JS on client side to manage, and I haven't been able to do a project yet to see how it unfolds, but the post was trying to think about how to get there and back again so I figured I would give my thoughts. I hope it helps and I would love to hear of other ways to manage the interactions.
无论如何,我确定这不是一个完美的想法,它需要客户端的一些 JS 来管理,而且我还没有能够做一个项目来看看它是如何展开的,但是帖子试图思考如何到那里再回来,所以我想我会给出我的想法。我希望它有所帮助,我很想听听其他管理互动的方法。
回答by oguzh4n
You don't need mapping viewmodel to domain because your viewmodel may be created more than domain model. Viewmodels optimized for screen (ui) and different from domain model.
您不需要将视图模型映射到域,因为您的视图模型可能比域模型创建的更多。针对屏幕 (ui) 优化的视图模型,与域模型不同。
http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/
http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/

