asp.net-mvc - 如何使用 asp.net mvc View 模型和数据注释属性保持 DRY?

标签 asp.net-mvc

如何使用 Asp.Net MVC 的 asp.net mvc View 模型和数据注释(验证、显示和数据建模)属性保持 DRY?我已经将模型对象以及特定于 Action 的 View 模型传递给 View 。我发现两个方向在试图保持干燥方面都有一些问题。

  • 使用模型对象作为您的 View 模型:这在简单情况下工作正常,并且允许您在每个模型对象上只编写一次数据注释属性。当您拥有需要多个对象类型的复杂 View 时,就会出现问题。由此产生的 View 模型架构是使用 View 模型类和实际模型类的混合体。此外,此方法可以将模型属性公开给您不想要的 View 。
  • 每个 Action 使用唯一的 View 模型类: View 模型类只包含 View 特定的属性,用数据注释属性修饰。根据我的经验,这种方法并没有被证明是非常枯燥的,因为数据注释属性往往会在 View 模型类中重复。例如,New 和 Edit 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/

    相关文章:

    c# - 如何在 MVC 中读取 DataSourceRequest 以进行过滤和排序

    asp.net-mvc - 我应该为每个请求使用一个 HttpClient 实例还是一个来处理我的所有请求?

    javascript - 我的启动项目中的 JS 文件又出现 'The Breakpoint will not currently be hit' 错误

    asp.net - ASP.NET MVC : Redirect to a view if certain condition is not met

    c# - 对象不能从 DBNull 分配给其他类型

    javascript - RAZOR - 从包含 HTML 的变量中删除图像标签

    asp.net-mvc - 如果未绑定(bind),MVC4 Razor 会丢失用户 ID

    c# - 带有依赖注入(inject)的 Telerik Reporting ObjectDataSource

    c# - StructureMap 无法加载文件或程序集

    c# - "' 无法加载文件或程序集 'Elmah' 或其依赖项之一。在NuGet中使用Elmah.MVC后系统找不到指定''的文件