问题
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