c# - ModelState 验证检查多个 bool 属性

标签 c# asp.net-mvc viewmodel model-validation

我的 View 模型具有多个 bool 属性,在我的 Controller 中,我在进入服务层之前检查了ModelState.IsValid。现在我想让 ModelState.IsValid 返回 false 如果没有 bool 属性设置为 true,有没有办法实现它?

这是我的示例类

public class Role {

   public int Id {get; set;}

   [Required(ErrorMessage = "Please enter a role name")]
   public string Name {get; set;}

   public bool IsCreator {get; set;}

   public bool IsEditor {get; set;}

   public bool IsPublisher {get; set;}
}

最佳答案

我会在模型上实现您自己的验证方法。你的模型最终会看起来像这样:

public class Role : IValidatableObject {
   public int Id {get; set;}

   [Required(ErrorMessage = "Please enter a role name")]
   public string Name {get; set;}

   public bool IsCreator {get; set;}

   public bool IsEditor {get; set;}

   public bool IsPublisher {get; set;}

   public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
       if (!this.IsCreator && !this.IsEditor && !this.IsPublisher)) {
           yield return new ValidationResult("You must be a creator, editor or publisher");
       }
   }
}

注意模型如何:

  1. 工具 IValidateableObject
  2. 有一个名为 Validate 的方法它返回类型 IEnumerable<ValidationResult>

在模型绑定(bind)过程中,将自动调用此方法,如果返回验证结果,您的ModelState将不再有效。因此,在 Controller 中使用这个熟悉的代码将确保您不会采取任何操作,除非您的自定义条件得到验证:

public class SomeController {
    public ActionResult SomeAction() {
        if (ModelState.IsValid) {
            //Do your stuff!
        }
    }
}

关于c# - ModelState 验证检查多个 bool 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319014/

相关文章:

c# - 反序列化从 Azure 表检索的 DynamicTableEntity

c# - 检测何时在 Windows 中卸载应用程序

jquery - 在一个请求中上传多个文件 Dropzone 发送两个请求

android - 如何通过 Android/Kotlin App 上的 Koin 注入(inject)在 BaseActivity 中初始化/注入(inject)通用 ViewModel

c# - 您可以将不同的 View 模型发送到 View 吗?

c# - 在文本中格式化 C# 代码,例如 Visual Studio

c# - 使用 IComparer 进行分组和排序

asp.net-mvc - asp.net mvc中嵌套属性的模型绑定(bind)

asp.net-mvc - ASP.NET MVC DDD 应用程序中的组合根

c# - Prism MVVM ViewModel属性支持字段作为模型的属性