下面是我为可空DateTime
属性创建的显示模板。我把它存储在Views\Shared\EditorTemplates
文件夹中。此模板的名称为DisplayNullableDate.cshtml
。
@model DateTime?
@Html.Label("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), new { @class = "form-control" })
我在Details
页面上调用此模板,但是它不起作用。我还在网页上显示它的时间。
<tr>
<td>@Html.DisplayFor(model => model.RelationshipCode1.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate1" })</td>
<td>@Html.DisplayFor(model => model.RelationshipCode1.RelationshipId, new { @class = "relDistCode1", maxlength = 3 })</td>
</tr>
<tr>
<td>@Html.DisplayFor(model => model.RelationshipCode2.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate2" })</td>
<td>@Html.DisplayFor(model => model.RelationshipCode2.RelationshipId, new { @class = "relDistCode2", maxlength = 3 })</td>
</tr>
<tr>
<td>@Html.DisplayFor(model => model.RelationshipCode3.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate3" })</td>
<td>@Html.DisplayFor(model => model.RelationshipCode3.RelationshipId, new { @class = "relDistCode3", maxlength = 3 })</td>
</tr>
<tr>
<td>@Html.DisplayFor(model => model.RelationshipCode4.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate4" })</td>
<td>@Html.DisplayFor(model => model.RelationshipCode4.RelationshipId, new { @class = "relDistCode4", maxlength = 3 })</td>
</tr>
<tr>
<td>@Html.DisplayFor(model => model.RelationshipCode5.EffectiveDate, "DisplayNullableDate", new { @class = "relCodeDate5" })</td>
<td>@Html.DisplayFor(model => model.RelationshipCode5.RelationshipId, new { @class = "relDistCode5", maxlength = 3 })</td>
</tr>
我在同一个Shared\EditorTemplates
文件夹中为NullableDate.cshtml
名称设置了同一个可空属性的另一个模板。我不认为这会干扰,但我会以任何方式发布它以防万一。
@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), new { @class = "form-control" })
修改
为了更好的衡量,这里是现在的模型属性。不幸的是,我不能让这种显示格式装饰工作。
[DisplayName("Effective Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public Nullable<System.DateTime> EffectiveDate { get; set; }
答案 0 :(得分:0)
我认为您需要使用[UIHint("NullableDate")]
属性修饰模型的属性。
答案 1 :(得分:0)
当我在DateTime字段中有空值时,这个DisplayTemplate最终为我工作:
@model DateTime?
@((@Model != null) ? Model.Value.ToString("MM/dd/yyyy") : "{n/a}" )
当值为null时,将替换为字符串:{n / a}