Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Html.DisplayFor - DateFormat ("mm/dd/yyyy")

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

like image 203
Nick Kahn Avatar asked Jan 23 '15 16:01

Nick Kahn


People also ask

What is HTML DisplayFor?

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.

How do I change the date format in razor view?

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)]

What is the format of datetime?

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".


1 Answers

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 DateTimes, 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") } 
like image 104
Chris Pratt Avatar answered Oct 13 '22 19:10

Chris Pratt