Home > DeveloperSection > Forums > @Html.DisplayFor - DateFormat (“mm/dd/yyyy”)
Alex Leblois
Alex Leblois

Total Post:67

Points:471
Posted on    April-15-2015 7:08 AM

 .NET C# 
Ratings:


 1 Reply(s)
 3959  View(s)
Rate this:

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



Kamlakar Singh
Kamlakar Singh

Total Post:28

Points:196
Posted on    April-15-2015 7:45 AM

If you use DisplayFor, then you have to either define the format via the DisplayFormat attribute or use a custom display template.

 

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]

public DateTime? AuditDate { get; set; }

Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml:

 

@model DateTime?

if (Model.HasValue)

{

    @Model.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(DateType.Date)]

public DateTime? AuditDate { get; set; }

The final option is to just not use DisplayFor and just render the property directly:

 

@if (Model.AuditDate.HasValue)

{

    @Model.AuditDate.Value.ToString("MM/dd/yyyy")

}


Don't want to miss updates? Please click the below button!

Follow MindStick