asp.net-mvcvalidationcheckboxdata-annotations

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


I've got a view model like this:

public class SignUpViewModel
{
    [Required(ErrorMessage = "Bitte lesen und akzeptieren Sie die AGB.")]
    [DisplayName("Ich habe die AGB gelesen und akzeptiere diese.")]
    public bool AgreesWithTerms { get; set; }
}

The view markup code:

<%= Html.CheckBoxFor(m => m.AgreesWithTerms) %>
<%= Html.LabelFor(m => m.AgreesWithTerms)%>

The result:

No validation is executed. That's okay so far because bool is a value type and never null. But even if I make AgreesWithTerms nullable it won't work because the compiler shouts

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."

So, what's the correct way to handle this?


Solution

  • I got it by creating a custom attribute:

    public class BooleanRequiredAttribute : RequiredAttribute 
    {
        public override bool IsValid(object value)
        {
            return value != null && (bool) value;
        }
    }