have a simple ViewModel with three properties like so:
public bool RememberMe { get; set; }
In my view I have a simple @Html.CheckBoxFor(p => p.RememberMe)
I am using Client Side validation enabled using Html.EnableClientValidation();
Why is this being set as a required field?
Try a nullable bool.
public bool? RememberMe { get; set; }
With reference types there are a number of default validation rules applied. If a reference type is not nullable, it becomes required by default. The best illustration of this is if you use a textbox to display some properties (not something you would do in 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)
You can see from a view source what happens 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">
The nullable bool has no validation attributes, whereas the bool has a data-val-required
tag. The int has a data-val-required
tag and a data-val-number
attribute
Of course, on a checkbox this is all pretty redundant as it can only be checked (true) or not checked (false) so a required tag isn't much use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With