库应该返回域模型,无法查看模型。就模型和视图模型之间的映射而言,我个人使用AutoMapper,所以我有一个单独的映射层,但是此层是从控制器调用的。
下面是一个典型的GET控制器动作可能什么样子:
public ActionResult Foo(int id)
{
// the controller queries the repository to retrieve a domain model
Bar domainModel = Repository.Get(id);
// The controller converts the domain model to a view model
// In this example I use AutoMapper, so the controller actually delegates
// this mapping to AutoMapper but if you don't have a separate mapping layer
// you could do the mapping here as well.
BarViewModel viewModel = Mapper.Map<Bar, BarViewModel>(domainModel);
// The controller passes a view model to the view
return View(viewModel);
}
这当然可以通过自定义操作过滤器被缩短,以避免重复映射逻辑:
[AutoMap(typeof(Bar), typeof(BarViewModel))]
public ActionResult Foo(int id)
{
Bar domainModel = Repository.Get(id);
return View(domainModel);
}
的自动地图定制动作过滤器订阅OnActionExecuted事件,拦截传递给视图结果的模型,调用映射层(在我的情况下为AutoMapper)将其转换为视图模型并将其替换为视图。该视图当然强烈地键入到视图模型中。
我的[回复] [1]这个问题应该解释一下如何做得更好。 [1]:http://stackoverflow.com/questions/3747383/best-practices-to-partition-model-code-to-logical-parts-in-mvc-which-is-the- bes/3747474#3747474 – 2012-07-13 12:06:48