Referencing the answer in this post I added /Views/Shared/DisplayTemplates and added a partial view called ShortDateTime.cshtml as shown below:
@model System.DateTime
@Model.ToShortDateString()
When the model contains a value this works and the formatted date is displayed correctly:
@Html.DisplayFor(modelItem => item.BirthDate, "ShortDateTime")
However, if a null value is returned a 'System.InvalidOperationException' is thrown. Indicating:
{"The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'."}
My first inclination was to use an if statement inside the partial view but it didn't seem to matter. Without referencing the template null values are handled as in:
@Html.DisplayFor(modelItem => item.BirthDate)
but the original issue of formatting remains. When I try to put conditional formatting in the View as follows, it doesn't work but I hoping it's just a syntax thing.
@Html.DisplayFor(modelItem => item.BirthDate == null) ? string.Empty : (modelItem => item.BirthDate, "ShortDateTime"))
The above results in a different 'System.InvalidOperationException':
{"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."}
So, is there a way to do conditional formatting in the View to generate just the date from a DateTime value?