ModelState验证检查多个布尔属性



我有多个布尔属性的视图模型,在我的控制器中,我在进入服务层之前检查了ModelState.IsValid。现在我想让ModelState.IsValid返回false如果没有布尔属性设置为真,有办法让它发生吗?

下面是我的示例类
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>

在模型绑定过程中,此方法将被自动调用,如果返回验证结果,您的ModelState将不再有效。所以在你的控制器中使用这段熟悉的代码将确保你不会采取任何行动,除非你的自定义条件检查出来:

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

您可以扩展ValidationAttribute:

public class MustBeCreatorEditorPublisherAttribute : ValidationAttribute
{
    public NoJoeOnMondaysAttribute() { ErrorMessage = "You must be a creator, editor or publisher"; }
    public override bool IsValid(object value)
    {
        using (Role role = value as Role)
        {
            return (role.IsCreator || role.IsEditor || role.IsPublisher);
        }
        return base.IsValid(value);
    }
}

你的模型:

[MustBeCreatorEditorPublisher]
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; }
}

相关内容

  • 没有找到相关文章

最新更新