Pr0*_*r0n 11 c# asp.net-mvc razor
我正在尝试在MVC中格式化一些DateTimes,但DisplayFormat没有应用于Nullable对象,我无法弄清楚为什么.它在CreatedDateTime上工作得很好,但没有LastModifiedDateTime
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy hh:mm tt}")]
public DateTime CreatedDateTime { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy hh:mm tt}")]
public Nullable<DateTime> LastModifiedDateTime { get; set; }
Run Code Online (Sandbox Code Playgroud)
以下是视图
<div class="editor-field">
@Html.DisplayFor(model => model.CreatedDateTime)
<br />
@Html.Raw(TimeAgo.getStringTime(Model.CreatedDateTime))
</div>
@if (Model.LastModifiedDateTime.HasValue)
{
<div class="editor-label">
@Html.LabelFor(model => model.LastModifiedDateTime)
</div>
<div class="editor-field">
@Html.DisplayFor(model => model.LastModifiedDateTime)
<br />
@Html.Raw(TimeAgo.getStringTime(Model.LastModifiedDateTime.Value)) By: @Html.DisplayFor(model => model.LastModifiedBy)
</div>
}
Run Code Online (Sandbox Code Playgroud)
如果我理解你的意图是正确的(我希望我做到了),那么你可以通过放置模板来为Nullable创建一个显示模板,Views/Shared/DisplayTemplates/DateTime.cshtml
并按如下方式定义:
@model System.DateTime?
@Html.Label("", Model.HasValue ? Model.Value.ToString("MM/dd/yy hh:mm tt") : string.Empty)
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助.
编辑
您可以为同一类型设置多个显示模板,并指定按名称使用哪一个,所以假设您有:
Views/Shared/DisplayTemplates/Name1.cshtml
Views/Shared/DisplayTemplates/Name2.cshtml
然后您可以将它们称为:
@Html.DisplayFor(model => model.LastModifiedDateTime, "Name1")
@Html.DisplayFor(model => model.LastModifiedDateTime, "Name2")
Run Code Online (Sandbox Code Playgroud)