Date formatting for the MVC “DisplayFor” tag

In my view, I had a date that I was displaying using DisplayFor

@Html.DisplayFor(modelItem => item.TranDate)

It was including the time, which I didn’t want. So I tried to include a date format like so:

@Html.DisplayFor(modelItem => item.TranDate, "{0:MM/dd/yyyy}")

This didn’t work, but after looking at the various overloads, it wouldn’t – there was no overload that accepted a format string like there was for TextboxFor, where the format string was working. Instead, what I had to do was add a DisplayFormat tag to the field definition in the model:

public class ServiceVM {
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime TranDate { get; set; }
  1. A night’s activities | Wunderhund

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: