ASP.NET MVC架构:视图模型通过组合,继承或复制? [英] ASP.NET MVC Architecture : ViewModel by composition, inheritance or duplication?

查看:171
本文介绍了ASP.NET MVC架构:视图模型通过组合,继承或复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC 3和c一实体框架4.1 $ C $。

I'm using ASP.NET MVC 3 and Entity Framework 4.1 Code First.

让我们说我有一个用户单位:

Let's say I have a User entity :

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }        
}

当编辑是我的 UserController的我想添加一个 PasswordConfirmation 字段并验证 PasswordConfirmation ==密码

When editing it in my UserController I want to add a PasswordConfirmation field and verify that PasswordConfirmation == Password

我的第一个尝试是:

public class EditUserModel
{
    [Required]
    public User User { get; set; }

    [Compare("User.Password", ErrorMessage = "Passwords don't match.")]
    public string PasswordConfirmation { get; set; }
}

在这种情况下,客户端验证的作品,但编辑:客户端验证工作是一个巧合)的不能正常工作并在服务器端验证失败以下消息:找不到一个名为user.password的属性

In this case the client side validation works but ( client side validation working was a coincidence.) doesn't work and the server side validation fails with the following message : Could not find a property named User.Password

编辑:我认为最好的解决办法,在这种情况下,是创建一个自定义的 CompareAttribute

I think the best solution, in this case, would be to create a custom CompareAttribute

实施 IValidatableObject

Implementing IValidatableObject

public class EditUserModel : IValidatableObject
{
    [Required]
    public User User { get; set; }
    public string PasswordConfirmation { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(this.PasswordConfirmation != this.User.Password)
            return new[] { new ValidationResult("Passwords don't match", new[] { "PasswordConfirmation " }) };

        return new ValidationResult[0];
    }
}

在这种情况下,服务器端验证工作原理但是客户端验证无法正常工作了。实施 IClientValidatable 好像有点太复杂了,我preFER没有在这种情况下,客户端验证。

In this case the server side validation works but the client side validation doesn't work anymore. Implementing IClientValidatable seems a bit too complicated and I prefer not having client side validation in this case.

public class EditUserModel : User
{
    [Compare("Password", ErrorMessage = "Passwords don't match.")]
    public string PasswordConfirmation  { get; set; }
}

在尝试直接保存 EditUserModel 使用EF它不工作,我得到了一些一些错误信息的 EditUserModel 元数据,所以我使用的 AutoMapper 的从用户转换为 EditUserModel 和向后。 该解决方案的,但它更加复杂,因为我必须从模型转换为视图模型和倒退。

When trying to directly save EditUserModel using EF it doesn't work, I get some some error message about the EditUserModel metadata so I'm using AutoMapper to convert from User to EditUserModel and backwards. This solution works but it more complex because I have to convert from the model to the view model and backwards.

(由马尔特CLASEN建议)

视图模式将有模式和额外的人的所有属性。的 AutoMapper 的可用于从一种转换为另一种。

The view model would have all the properties of the model plus additional ones. AutoMapper can be used to convert from one to another.

public class EditUserModel {    
  public string Name { get; set; }    
  public string Email { get; set; }    
  public string Password { get; set; }   
  [Compare("Password", ErrorMessage = "Passwords don't match.")]     
  public string ConfirmPassword { get; set; }        
}

这是我最不喜欢的,因为code重叠(干)

This is the solution I like the least because of code duplication (DRY)

问题

有哪些优点和继承,组成和重复利弊在这种情况下?

What are the pros and cons of inheritance, composition and duplication in this case ?

有一个简单的办法有两个客户端和服务器端验证,而无需到模型转换为视图模型和倒退?

Is there a simple way to have both client side and server side validation without having to convert the model to the view model and backwards ?

推荐答案

已经在努力与这个问题之前,我在走与所有三个不同的实例。在一般情况下,大多数我见过的意见,有利于重复在MVC项目中,有一个ViewModel专门构建了每个视图。通过这种方式,你会使用的惯例是一样的东西 UserDetailsViewModel UserCreateViewModel 。正如你所说,在这一点上AutoMapper或其他自动映射工具将被用于从您的域对象转换为这些平板的ViewModels。

Having struggled with this question before, I have in various instances gone with all three. In general, most of the opinions I've seen favor duplication in an MVC project, with a ViewModel constructed specifically for each view. In this manner the convention you'd use is something like UserDetailsViewModel and UserCreateViewModel. As you said, at that point AutoMapper or some other auto mapping tool would be used to convert from your domain objects to these flat ViewModels.

虽然我也一样,不喜欢重复code,我也不喜欢污染我的域对象与验证或其他视图特定的属性。另外一个优势,但无可否认人们几乎没有人会不得不抗衡(不考虑所有的优点说),是你可以操纵在某些方面你的域对象,而不必操纵你的ViewModels。我提到,因为它经常被引用的,而不是因为它承载的重量对我来说。

While I, too, don't like repeating code, I also don't like polluting my domain objects with validation or other view-specific attributes. Another advantage, though admittedly one almost nobody would ever have to contend with (regardless of what all the pros say), is that you can manipulate your domain objects in some ways without necessarily manipulating your ViewModels. I mention that because it's commonly cited, not because it carries much weight for me.

最后,用一个真正的平视图模型,使清洁的标记。当我用成分,我经常创建具有名称是类似于 User.Address.Street HTML元素出现的错误。扁平视图模型降低了,至少我这样做(我知道,我总是可以使用的HtmlHelper程序创建的元素,但是这并不总是可行的)。

Lastly, using a truly flat ViewModel makes for cleaner markup. When I've used composition, I've often made errors creating HTML elements with names that are something like User.Address.Street. A flat ViewModel reduces at least my likelihood of doing that (I know, I could always use HtmlHelper routines to create elements, but that's not always feasible).

我最近的项目也纷纷pretty的多少需要单独的ViewModels这些天反正。他们都被NHibernate的基础,并在NHibernate的对象代理的使用使得它不可能直接使用他们的意见。

My recent projects have also pretty much required separate ViewModels these days anyway. They've all been NHibernate-based, and the use of proxies on NHibernate objects makes it not possible to use them directly for views.

更新 - 在这里是一个很好的文章中,我已经在过去提到:<一href="http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx">http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

Update - here's a good article I've referred to in the past: http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

这篇关于ASP.NET MVC架构:视图模型通过组合,继承或复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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