EditorFor/CheckBoxFor boolean adds data-val-requir

2020-07-08 06:47发布

问题:

My model class has a bool property without a Required attribute:

public class Test
{        
    public bool TestBool1 { get; set; }
}

Then in my razor view I am using EditorFor (Same thing happens with CheckBoxFor as well):

<div>
    @Html.LabelFor(m => m.TestBool1)
    @Html.EditorFor(m => m.TestBool1)
</div>

This results in the following HTML:

<div>
    <label for="TestBool1">TestBool1</label>
    <input class="check-box" data-val="true" data-val-required="The TestBool1 field is required." id="TestBool1" name="TestBool1" type="checkbox" value="true">
    <input name="TestBool1" type="hidden" value="false">
</div>

Where is the data-val-required html attribute coming from?

Is there a way to stop it doing this without using @Html.CheckBox("TestBool1", Model.TestBool1) and setting the type to bool??

回答1:

from this answer Data annotations, why does boolean prop.IsRequired always equal true

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Add this to your application_start. By default MVC adds [Required] to non-nullable value types (because you can't convert null into a bool, it must be a bool?)

you can prevent it happening, but as you will always send the bool (true or false) I usually leave it