C# DisplayFormat不适用于Nullable<;日期时间>;
我试图在MVC中格式化一些日期时间,但是DisplayFormat没有应用于可为空的对象,我不知道为什么。它在CreatedDateTime上运行得非常好,但在LastModifiedDateTime上运行得不好C# DisplayFormat不适用于Nullable<;日期时间>;,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我试图在MVC中格式化一些日期时间,但是DisplayFormat没有应用于可为空的对象,我不知道为什么。它在CreatedDateTime上运行得非常好,但在LastModifiedDateTime上运行得不好 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy hh:mm tt}")] public DateTime CreatedDateTime { get; set; } [Displa
[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; }
[DisplayFormat(ApplyFormatInEditMode=true,DataFormatString=“{0:MM/dd/yy hh:MM tt}”)]
公共日期时间CreatedDateTime{get;set;}
[DisplayFormat(ApplyFormatInEditMode=true,DataFormatString=“{0:MM/dd/yy hh:MM tt}”)]
公共可为空的LastModifiedDateTime{get;set;}
下面是视图
<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>
}
@DisplayFor(model=>model.CreatedDateTime)
@Html.Raw(TimeAgo.getStringTime(Model.CreatedDateTime))
@if(Model.LastModifiedDateTime.HasValue)
{
@LabelFor(model=>model.LastModifiedDateTime)
@DisplayFor(model=>model.LastModifiedDateTime)
@Html.Raw(TimeAgo.getStringTime(Model.LastModifiedDateTime.Value))作者:@Html.DisplayFor(Model=>Model.LastModifiedBy)
}
如果我理解您的意图是正确的(我希望我理解了),那么您可以通过将模板放置在视图/Shared/DisplayTemplates/DateTime.cshtml中,并按照以下方式定义它,从而获得可为null的显示模板:
@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")
我认为格式化nullableDateTime
最简单的方法是使用ValueFor
方法:
@Html.ValueFor(m => m.CreatedDateTime , "{0:MM/dd/yy hh:mm tt}")
@Html.ValueFor(m => m.LastModifiedDateTime , "{0:MM/dd/yy hh:mm tt}")
将ValueFor
方法与TimeSpan
或Nullable
一起使用时,冒号字符“:”必须转义:
@Html.ValueFor(m => m.MyTimeSpan, "{0:hh':'mm}")
如果使用DateTime?
而不是Nullable
,将其更改为DateTime,是否会失败?没有效果。@TyCobbDateTime?
和Nullable
是相同的。这解决了问题,但是如果我希望DateTime在不同的位置显示不同,该怎么办?这是目前最好的“解决方法”,谢谢。但实际上需要某种扩展来为整个应用程序通用地执行此操作,并支持现有的数据注释属性。但我要先检查一下MVC5,看看微软是否已经在核心中实现了这一点。我经常使用可空类型,根据我的经验,这是一个核心要求。