Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditorFor/CheckBoxFor boolean adds data-val-required attribute to HTML without required attribute being added to model

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??

like image 701
Richard Dalton Avatar asked Mar 14 '13 10:03

Richard Dalton


1 Answers

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

like image 152
Pharabus Avatar answered Sep 28 '22 09:09

Pharabus