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

ぐ巨炮叔叔 提交于 2019-12-01 08:20:59

问题


I have a model containing a boolean with no [Required] attribute

public bool IsOptedIn { get; set; }

I have overriden Object.cshtml as follows and am using @Html.EditorForModel() to generate my form

@{
    var properties = ViewData.ModelMetadata.Properties
                        .Where(prop => prop.ShowForEdit && !ViewData.TemplateInfo.Visited(prop));    
}

@foreach (var prop in properties)
{
    var hasModelStateError = ViewContext.ViewData.ModelState.Any(m => m.Key == prop.PropertyName) 
        && ViewContext.ViewData.ModelState[prop.PropertyName].Errors != null
        && ViewContext.ViewData.ModelState[prop.PropertyName].Errors.Count > 0;  
    <div class="control-group 
        @(hasModelStateError ? "error" : string.Empty) 
        @prop.PropertyName.ToLower()">
        @if (prop.IsReadOnly)
        {
            <b>@prop.GetDisplayName()</b>
            @Html.Display(prop.PropertyName)
        }
        else if (prop.HideSurroundingHtml)
        {
            @Html.Editor(prop.PropertyName)                    
        }
        else
        {
            <label class="control-label">
                @prop.GetDisplayName()
                @if (prop.IsRequired)
                {
                    <span class="required">*</span> 
                }            
            </label>                     
            <div class="controls">
                @Html.Editor(prop.PropertyName)             
                @if (hasModelStateError)
                {
                    <p class="alert alert-block">
                        @Html.ValidationMessage(prop.PropertyName)
                    </p>
                }
                @if (!string.IsNullOrWhiteSpace(prop.Description))
                {
                    <p class="help-block">
                        @prop.Description
                    </p>              
                }                    
            </div>
        }            
    </div>     
}

I am finding that bools in my model are always being marked as required. Why is this and how can I stop it happening?


回答1:


DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; 

Add this line to your Application_Start method from Global.asax. By default MVC adds [Required] attribute to non-nullable value types (because you can't convert a null into a bool, it must be a bool).



来源:https://stackoverflow.com/questions/13957855/data-annotations-why-does-boolean-prop-isrequired-always-equal-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!