In ASP.NET MVC3 how do you stay DRY with very similar but slightly different viewmodels?

强颜欢笑 提交于 2020-01-05 07:55:13

问题


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
}

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.

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.

What are other ways to keep this DRY?


回答1:


To benefit a validation context (e.g. validating objects in different contexts), I strongly recommend using FluentValidation library.




回答2:


You could implement a custom RequiredIf validation attribute, or you could implement IValidatableObject.



来源:https://stackoverflow.com/questions/8987128/in-asp-net-mvc3-how-do-you-stay-dry-with-very-similar-but-slightly-different-vie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!