如何使用 Asp.Net MVC 的 asp.net mvc View 模型和数据注释(验证、显示和数据建模)属性保持 DRY?我已经将模型对象以及特定于 Action 的 View 模型传递给 View 。我发现两个方向在试图保持干燥方面都有一些问题。
如何使用 asp.net mvc View 模型和数据注释属性保持 DRY?
最佳答案
一个不错的选择是从 DataAnnotations 切换到 Fluent Validation .
它允许您将常见的验证逻辑封装在一个类中,您可以稍后将其应用于您的模型。
来自 documentation :
[Validator(typeof(PersonValidator))]
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
关于asp.net-mvc - 如何使用 asp.net mvc View 模型和数据注释属性保持 DRY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4377578/