作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我试图在 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; }
下面是 View
<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>
}
最佳答案
如果我理解你的意图是正确的(我希望我理解了),那么你可以通过将你的模板放在 Views/Shared/DisplayTemplates/DateTime.cshtml
中并定义它来为 Nullable 提供一个显示模板以下内容:
@model System.DateTime?
@Html.Label("", Model.HasValue ? Model.Value.ToString("MM/dd/yy hh:mm tt") : string.Empty)
希望对您有所帮助。
编辑
同一类型可以有多个显示模板,并通过名称指定要使用的模板,假设您有:
Views/Shared/DisplayTemplates/Name1.cshtml
Views/Shared/DisplayTemplates/Name2.cshtml
然后你可以这样称呼他们:
@Html.DisplayFor(model => model.LastModifiedDateTime, "Name1")
@Html.DisplayFor(model => model.LastModifiedDateTime, "Name2")
关于c# - DisplayFormat 不适用于 Nullable<DateTime>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16908910/
我是一名优秀的程序员,十分优秀!