How to handle Booleans/CheckBoxes in ASP.NET MVC 2 with DataAnnotations?

后端 未结 12 1187
慢半拍i
慢半拍i 2020-12-04 10:09

I\'ve got a view model like this:

public class SignUpViewModel
{
    [Required(ErrorMessage = \"Bitte lesen und akzeptieren Sie die AGB.\")]
    [DisplayName         


        
12条回答
  •  猫巷女王i
    2020-12-04 10:12

    My solution is this simple custom attribute for boolean values:

    public class BooleanAttribute : ValidationAttribute
    {
        public bool Value
        {
            get;
            set;
        }
    
        public override bool IsValid(object value)
        {
            return value != null && value is bool && (bool)value == Value;
        }
    }
    

    Then you can use it like this in your model:

    [Required]
    [Boolean(Value = true, ErrorMessage = "You must accept the terms and conditions")]
    [DisplayName("Accept terms and conditions")]
    public bool AcceptsTerms { get; set; }
    

提交回复
热议问题