I have the following razor code that I want to have mm/dd/yyyy
date format:
Audit Date: @Html.DisplayFor(Model => Model.AuditDate)
I have tried number of different approaches but none of that approaches works in my situation
my AuditDate is a DateTime?
type
I have tried something like this and got this error:
@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Tried this:
@Html.DisplayFor(Model => Model.AuditDate.ToString("mm/dd/yyyy"))
No overload for method 'ToString' takes 1 arguments
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.
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)]
For example, the "d" standard format string indicates that a date and time value is to be displayed using a short date pattern. For the invariant culture, this pattern is "MM/dd/yyyy". For the fr-FR culture, it is "dd/MM/yyyy". For the ja-JP culture, it is "yyyy/MM/dd".
If you use DisplayFor
, then you have to either define the format via the DisplayFormat
attribute or use a custom display template. (A full list of preset DisplayFormatString
's can be found here.)
[DisplayFormat(DataFormatString = "{0:d}")] public DateTime? AuditDate { get; set; }
Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml
:
@model DateTime? @if (Model.HasValue) { @Model.Value.ToString("MM/dd/yyyy") }
That will apply to all DateTime
s, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml
and the DataType
attribute on your property:
[DataType(DataType.Date)] public DateTime? AuditDate { get; set; }
The final option is to not use DisplayFor
and instead render the property directly:
@if (Model.AuditDate.HasValue) { @Model.AuditDate.Value.ToString("MM/dd/yyyy") }
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