庫應該返回域模型,無法查看模型。就模型和視圖模型之間的映射而言,我個人使用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