2

我有一个模型包含一个没有[Required]属性的布尔值

public bool IsOptedIn { get; set; }

我已Object.cshtml按如下方式覆盖并@Html.EditorForModel()用于生成我的表单

@{
    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>     
}

我发现我的模型中的布尔值总是按要求标记。为什么会这样,我怎样才能阻止它发生?

4

1 回答 1

8
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false; 

将此行添加到您的Application_Start方法中Global.asax。默认情况下,MVC 将[Required]属性添加到不可为空的值类型(因为您不能将 a 转换null为 a bool,它必须是 a bool)。

于 2012-12-19T17:42:46.853 回答