Bool property without attribute Required attribute

have a simple ViewModel with three such properties:

public bool RememberMe { get; set; } 

In my opinion, I have a simple @Html.CheckBoxFor(p => p.RememberMe) I use client-side validation using Html.EnableClientValidation();

Why is this specified as a required field?

+7
source share
2 answers

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.

+8
source
 @Html.CheckBoxFor(c => c.TermsAndConditions, new { required = "required" }) @Html.ValidationMessageFor(c => c.TermsAndConditions, "you must agree to terms and conditions of Service.)" 
-2
source

All Articles