简体   繁体   English

EditorFor / CheckBoxFor boolean将data-val-required属性添加到HTML,而不将必需属性添加到模型中

[英]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: 我的模型类有一个没有Required属性的bool属性:

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

Then in my razor view I am using EditorFor (Same thing happens with CheckBoxFor as well): 然后在我的剃刀视图中我使用EditorFor(同样的事情也发生在CheckBoxFor上):

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

This results in the following HTML: 这导致以下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? data-val-required html属性来自哪里?

Is there a way to stop it doing this without using @Html.CheckBox("TestBool1", Model.TestBool1) and setting the type to bool? 有没有办法阻止它这样做而不使用@Html.CheckBox("TestBool1", Model.TestBool1)并将类型设置为bool? ?

from this answer Data annotations, why does boolean prop.IsRequired always equal true 从这个答案数据注释,为什么布尔prop.IsRequired始终等于true

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Add this to your application_start. 将其添加到您的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?) 默认情况下,MVC将[Required]添加到不可为空的值类型(因为你不能将null转换为bool,它必须是bool?)

you can prevent it happening, but as you will always send the bool (true or false) I usually leave it 你可以防止它发生,但因为你总是发送bool(真或假)我通常会离开它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM