问题
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