ASP.NET MVC 视图模型模式 [英] ASP.NET MVC ViewModel Pattern

查看:23
本文介绍了ASP.NET MVC 视图模型模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:为了使用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 示例应用程序

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

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 违规,但现在使用 ValueInjecter 我有干净的 ViewModel 和干映射代码

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

<小时>那是旧东西,不要使用它:
我制作了一个 ViewModel 模式,用于在 asp.net 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; }
...     

    }

推荐答案

有几件事困扰着我.

  1. 术语.ViewModel 在这种情况下是一个简单的视图数据,由控制器填充并稍后使用.View 对控制器一无所知,因为 ASP.NET MVC 基础结构负责选择控制器和适当的操作.控制器处理用户交互.我认为它看起来更像是 Passive 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.

希望这会有所帮助.

这篇关于ASP.NET MVC 视图模型模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆