DisplayFormat无法使用Nullable <datetime> </datetime>

时间:2013-06-04 02:29:04

标签: 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; }

以下是视图

   <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>
    }

2 个答案:

答案 0 :(得分:9)

如果我理解你的意图是正确的(我希望我这样做),那么你可以通过将模板放在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")

答案 1 :(得分:1)

我认为格式化可空DateTime的最简单方法是使用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}")

ValueForTimeSpan使用Nullable<TimeSpan>方法时,必须对冒号字符“:”进行转义:

@Html.ValueFor(m => m.MyTimeSpan, "{0:hh':'mm}")