@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


Solution 1:

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")
}

Solution 2:

If you are simply outputting the value of that model property, you don't need the DisplayFor html helper, just call it directly with the proper string formatting.

Audit Date: @Model.AuditDate.Value.ToString("d")

Should output

Audit Date: 1/21/2015

Lastly, your audit date could be null, so you should do the conditional check before you attempt to format a nullable value.

@if (item.AuditDate!= null) { @Model.AuditDate.Value.ToString("d")}

Googling the error that you are getting provides this answer, which shows that the error is from using the word Model in your Html helpers. For instance, using @Html.DisplayFor(Model=>Model.someProperty). Change these to use something else other than Model, for instance: @Html.DisplayFor(x=>x.someProperty) or change the capital M to a lowercase m in these helpers.

Solution 3:

I have been using this change in my code :

old code :

 <td>
  @Html.DisplayFor(modelItem => item.dataakt)
 </td>

new :

<td>
 @Convert.ToDateTime(item.dataakt).ToString("dd/MM/yyyy")
</td>

Solution 4:

You can use the [DisplayFormat] attribute on your view model as you want to apply this format for the whole project.

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<System.DateTime> Date { get; set; }