Preston Preston - 3 months ago 17
C# Question

DisplayFormat not working with Nullable<DateTime>

I'm trying to format some DateTimes in MVC but the DisplayFormat is not being applied to the Nullable object and I can't figure out why. It worked perfectly fine on CreatedDateTime but not 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; }


Below is the 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>
}

Answer

If I understood your intentions correct (I hope I did), then you can have a display template for Nullable by placing your template in Views/Shared/DisplayTemplates/DateTime.cshtml and define it like the following:

@model System.DateTime?
@Html.Label("", Model.HasValue ? Model.Value.ToString("MM/dd/yy hh:mm tt") : string.Empty)

I hope this helps.

EDIT

You can have multiple Display Templates for the same type and specify which one to use by name so let's say you have:

  • Views/Shared/DisplayTemplates/Name1.cshtml
  • Views/Shared/DisplayTemplates/Name2.cshtml

You can then call them like:

@Html.DisplayFor(model => model.LastModifiedDateTime, "Name1")
@Html.DisplayFor(model => model.LastModifiedDateTime, "Name2")