在ASP.NET MVC3中,如何使用非常相似但略有不同的视图模型来保持DRY状态? [英] In ASP.NET MVC3 how do you stay DRY with very similar but slightly different viewmodels?
问题描述
在构建应用程序时,我们创建了一个通用对象模型来存储一些值,目前,viewmodel看起来像这样:
In building an app, we created a generic object model to store some values, the viewmodel looks a bit like this at the moment:
public class FooViewModel {
public int ID { get; set; }
public byte FooType { get; set; }
[Required]
[Display(Name = "Bar Name")]
public string Name { get; set; }
[Required]
public string Email { get; set; }
//etc, etc
}
问题是:根据FooType,我们希望显示名称不同,并且类型1和2不需要电子邮件,而类型3和4则需要电子邮件.
The problem is: depending on the FooType, we want to have the Display Name to be different and the Email is not required for type 1 and 2, but is required for type 3 and 4.
We tried seperating out the properties that differ per type in to classes that inherit from this one, but the validation does a fallback on what is specified in the base type, so that didn't work.
当前,唯一的选择似乎是为每个FooType(以及单独的控制器和视图)创建一个视图模型,这导致大量代码重复.
Currently, the only option seems to be to create a viewmodel for each FooType (and also seperate controllers and view), which leads to a lot of code duplication.
还有什么其他方法可以保持此DRY?
What are other ways to keep this DRY?
推荐答案
为使验证上下文受益(例如,在不同上下文中验证对象),我强烈建议使用
To benefit a validation context (e.g. validating objects in different contexts), I strongly recommend using FluentValidation library.
这篇关于在ASP.NET MVC3中,如何使用非常相似但略有不同的视图模型来保持DRY状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!