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?
DisplayFor() The DisplayFor() helper method is a strongly typed extension method. It generates a html string for the model object property specified using a lambda expression.
php $orgDate = "2019-09-15"; $newDate = date("d-m-Y", strtotime($orgDate)); echo "New date format is: ". $newDate. " (MM-DD-YYYY)"; ?>
You can use the DisplayFormat data annotation attribute on the model property to specify the format and ensure that the format also applies when the value is in "edit mode" (a form control): [BindProperty, DisplayFormat(DataFormatString = "{0:yyyy-MM-ddTHH:mm}", ApplyFormatInEditMode = true)]
The HTML Markup consists of an ASP.Net GridView with three BoundField columns. The third BoundField column is bound to a DateTime field and the DataFormatString property is set to {0:dd/MM/yyyy} in order to display the DateTime field value in dd/MM/yyyy format.
The problem you're experiencing is that you are passing a null
value into a non-nullable model. Change the partial view's model to DateTime?
. For example:
@model DateTime?
@if (!Model.HasValue)
{
<text></text>
}
else
{
@Model.Value.ToShortDateString()
}
Hope this helps.
Have you tried this?
@if (modelItem.BirthDate != null) { Html.DisplayFor(modelItem => item.BirthDate, "ShortDateTime") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With