21

编辑:我做了一些更好的东西来填充和读取使用 ViewModels 的视图中的数据,称为ValueInjecterhttp://valueinjecter.codeplex.com/

它由http://prodinner.codeplex.com - 一个 ASP.net MVC 示例应用程序使用

您可以在 prodinner 中看到使用 ViewModel 的最佳方式

使用 ViewModel 存储映射逻辑并不是一个好主意,因为存在重复和 SRP 违规,但现在使用 ValueInjecter 我有干净的 ViewModel 和干映射代码


那是旧的东西,不要使用它:
我在 asp.net mvc 中创建了一个 ViewModel 模式来编辑东西,当你必须制作一个表单来编辑实体并且你必须在表单上放一些东西时,这个模式很有用 - downs 供用户选择一些值

    public class OrganisationBadViewModel
    {
        //paramterless constructor required, cuz we are gonna get an OrganisationViewModel object from the form in the post save method
        public OrganisationViewModel() : this(new Organisation()) {}
        public OrganisationViewModel(Organisation o)
        {
            Organisation = o;
            Country = new SelectList(LookupFacade.Country.GetAll(), "ID", "Description", CountryKey);  
        }       
        //that's the Type for whom i create the viewmodel
        public Organisation Organisation { get; set; }
...     

    }
4

4 回答 4

11

这看起来与 Wrox Professional ASP.NET MVC书中推荐的做法非常相似,该书的第一章可从上述 URL 免费获得。

从第 100 页开始,他们有一个关于ViewData 和 ViewModels的部分。

当控制器类决定将 HTML 响应呈现回客户端时,它负责将呈现响应所需的所有数据显式传递给视图模板。视图模板不应该执行任何数据检索或应用程序逻辑——而应该将自己限制为仅具有由控制器传递给它的模型/数据驱动的渲染代码。

[...]

当使用 [“ViewModel”] 模式时,我们会创建针对特定视图场景进行优化的强类型类,并公开视图模板所需的动态值/内容的属性。然后,我们的控制器类可以填充这些视图优化类并将其传递给我们的视图模板以供使用。这可以在视图模板中实现类型安全、编译时检查和编辑器智能感知。

摘自 Rob Connery 等人编写的由 Wrox 出版的 Professional ASP.NET MVC 1.0 的“第 1 章“书呆子晚餐””。原文可在http://tinyurl.com/aspnetmvc获得

于 2009-09-09T13:14:16.563 回答
9

There are couple of things that bother me.

  1. The terminology. ViewModel is this case is a simple view data that is populated and later consumed by controller. View knows nothing about controller as ASP.NET MVC infrastructure is responsible for selecting controllers and appropriate actions. Controller handles user interaction. I think it looks more like Passive View than ViewModel (I assume that by ViewModel you mean Model-View-ViewModel pattern).

  2. The details. The controller that populates view data is not supposed to know the details of how the view is implemented. However OrganisationViewModel.Country discloses unnecessary details (SelectListItem is pure view implementation detail). Thus making controller dependent on view implementation details. I think it should be changed to avoid it. Consider using some object that will hold the data for a country.

Hope this helps.

于 2009-09-08T08:20:16.327 回答
1

总的来说,我认为它看起来不错,并且为您的域对象创建视图模型通常是个好主意。

我没有查看每一行代码,但引起我注意的一件事是 OrganisationViewModel 的构造函数。我会使用以下方法重写它:

public OrganisationViewModel() : this(new Organisation()) { }

public OrganisationViewModel(Organisation o)
{
  Organisation = o;
  InitCollections();
}

这删除了一些重复的代码,因为您不必InitCollections()在两个构造函数中调用。当然,这只是一个小细节,与大意无关。

于 2009-09-01T07:54:50.723 回答
1

我们开始这样做了,但是我们的控制器开始变得怪异(因为我们的 ViewModel 不一定 1:1 映射到我们的数据库)。为了缓解这种情况,我们创建了 Mapper 类来创建 ViewModel,然后映射回绑定到数据库的数据。然后控制器只调用 Mapper 类方法。似乎运作良好。

于 2009-11-25T07:59:18.710 回答