1
我有一個包含有沒有一個布爾[Required]
屬性數據說明,爲什麼布爾總是prop.IsRequired等於真正
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>
}
我發現我的模型中的bools總是被標記爲需要。爲什麼會這樣,我該如何阻止它發生?
bool不能爲空。它必須是真或假。所以這就是爲什麼它需要。嘗試使用可空布爾(bool?)而不是常規bool –