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

后端 未结 12 1154
慢半拍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条回答
  •  一生所求
    2020-12-04 10:22

    I would create a validator for both Server AND Client side. Using MVC and unobtrusive form validation, this can be achieved simply by doing the following:

    Firstly, create a class in your project to perform the server side validation like so:

    public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
    {
        public override bool IsValid(object value)
        {
            if (value == null) return false;
            if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
            return (bool)value == true;
        }
    
        public override string FormatErrorMessage(string name)
        {
            return "The " + name + " field must be checked in order to continue.";
        }
    
        public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
                ValidationType = "enforcetrue"
            };
        }
    }
    

    Following this, annotate the appropriate property in your model:

    [EnforceTrue(ErrorMessage=@"Error Message")]
    public bool ThisMustBeTrue{ get; set; }
    

    And Finally, enable client side validation by adding the following script to your View:

    
    

    Note: We already created a method GetClientValidationRules which pushes our annotation to the view from our model.

提交回复
热议问题