Try the nullable bool.
public bool? RememberMe { get; set; }
With reference types, a number of default validation rules apply. If the reference type is not null, it becomes mandatory by default. The best illustration of this is to use a text box to display some properties (not what you would do on your site, but good for testing purposes):
Model:
public bool? MyBool { get; set; } public int MyInt { get; set; }
View:
@Html.TextBoxFor(p => p.MyBool) @Html.TextBoxFor(p => p.MyInt)
From the view source you can see what is happening on the page:
<input id="MyNullBool" name="MyNullBool" type="text" value=""> <input data-val="true" data-val-required="The MyBool field is required." id="MyBool" name="MyBool" type="text" value="False"> <input data-val="true" data-val-number="The field MyInt must be a number." data-val-required="The MyInt field is required." id="MyInt" name="MyInt" type="text" value="0">
Nullable bool has no validation attributes, while bool has a data-val-required tag. Int has a data-val-required tag and a data-val-number attribute
Of course, on the checkbox this is all quite redundant, since it can be checked (true) or not checked (false), so the required tag is not very useful.
Simon c
source share