【发布时间】:2011-12-18 02:05:07
【问题描述】:
我很好奇人们构建 ViewModel 的各种方式以及他们选择这种方法的原因。
我可以在这里想到几种方法:
-1。注入存储库 - 控制器加载模型并映射到 ViewModel。在这里,ViewModel 构造函数可以采用各种集合来为 ex 进行交互设置。在选择列表中,例如:
public CustomerController(ISomeRepository repository)
{
_repository = repository;
}
public ActionResult Create()
{
CustomerCreateViewModel model = new CustomerCreateViewModel(_repository.GetShipTypes,
_repository.GetStates);
..
..
}
-2。 ViewModelBuilder - 在控制器中注入或实例化注入存储库的实例。通过类似
的方式调用>var orderViewModel = orderViewModelBuilder.WithStates().Build(orderId);
或者,
var orderViewModel = orderViewModelBuilder.WithStates().Build(orderId);
-3。直接在控制器中(不需要代码 - 它很乱)
-4。其他一些服务(注入与否)返回控制器然后映射的域模型或 ViewModel(任何人这样做是为了返回一个没有特别命名/标注为 ViewModel 构建器类的视图模型?)
public JobCreateViewModel BuildJobCreateViewModel(int parentId)
{
JobCreateViewModel model = new JobCreateViewModel();
model.JobStatus = _unitOfWork.JobRepository.GetJobStatuses();
model.States=_unitOfWork.StateRepository.GetAll();
return model;
}
现在在回程中 - 关于验证您的视图模型 - 您是从基本 ViewModel 类继承以进行标准验证,还是在所有 ViewModel 之间复制您的验证(例如数据注释属性),或者只是依赖服务器端验证,以便可以针对您的域对象进行验证?
还有其他人吗?有更好的吗?为什么?
编辑 根据下面的链接,我确实找到了 Jimmy Bogard 的一篇关于 ViewModels 架构的好文章。虽然它没有直接解决上述问题,但对于任何来这里获取 ViewModel 信息的人来说,它都是一个很好的参考。 http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/
【问题讨论】:
-
这里有人反对 - 只是好奇为什么 - 有什么我可以澄清的吗?
-
在我的手机上,我在尝试加注星标时无意中点击了它——抱歉。现在撤消为时已晚。
标签: asp.net-mvc asp.net-mvc-3 model-view-controller viewmodel