ASP.NET MVC ViewModel模式

问题描述:

编辑:使用ViewModels ,使用 ValueInjecter 填充和读取视图中的数据,我做得更好。 http://valueinjecter.codeplex.com/

I made something much better to fill and read data from a view using ViewModels, called it ValueInjecter. http://valueinjecter.codeplex.com/

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

你可以看到使用ViewModel在prodinner中的最佳方法

it is used by http://prodinner.codeplex.com - an ASP.net MVC sample application

you can see the best way of using ViewModels in prodinner

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

using the ViewModel to store the mapping logic was not such a good idea because there was repetition and SRP violation, but now with the ValueInjecter I have clean ViewModels and dry mapping code



这是旧的东西,不要使用它:

我在asp.net中创建了一个ViewModel模式来编辑东西mvc
这个模式当您必须填写表单进行编辑实体时,您必须在表单上放置一些下拉列表以供用户选择某些值
    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; }
...     

    }


有几件事情打扰了我。

There are couple of things that bother me.


  1. 术语。 ViewModel是一个简单的视图数据,被安装并被控制器消耗。由于ASP.NET MVC基础架构负责选择控制器和适当的操作,View对于控制器一无所知。控制器处理用户交互。我认为它比ViewModel看起来更像被动视图(我认为ViewModel表示Model-View-ViewModel模式)。

  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).

详细信息。填充视图数据的控制器不应该知道视图的实现细节。然而OrganisationViewModel.Country公开了不必要的细节(SelectListItem是纯视图实现细节)。因此使控制器依赖于实现细节。我认为应该改变,以避免它。考虑使用一些可以保存一个国家的数据的对象。

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.

希望这有帮助。