How can I format a date for an EPiServer property rendered in a view?

1.3k views Asked by At

I'm working in EPiServer 7.5 with a partial view that displays news articles. In my NewsArticle class there is a DateTime property of DateUpdated which gets set when an article is saved. I'm able to expose this in the partial view using the PropertyFor method, like so:

@Html.PropertyFor(x => x.DateUpdated)

This gets rendered as: 11/19/2014 10:21:07 AM

What I would like to do is apply special formatting to the date, so that in the above case it would display "November 19, 2014". I tried appending .ToString() with a format to the @Html.PropertyFor(), but that did not work. One solution that I've considered is adding another property to the NewsArticle class which formats the date, but I would prefer to format it directly in the view. Is there a way to format this date from within the view?

Note, I am able to do this in the view, but I'm wondering if there is a more succinct way:

@model EPiServerExercise.Models.Pages.NewsArticle

@{
    string dateUpdated = Model.DateUpdated.ToString("MMMM d, yyyy");
}

<div class="newsArticleDate">@dateUpdated</div>

It just seems there should be an overload on @Html.PropertyFor, or something similar, to streamline this. Thanks.

1

There are 1 answers

0
Andreas On BEST ANSWER

I would create a display template in /Views/Shared/DisplayTemplates/DateTime.cshtml containing:

@model DateTime

@Model.ToString("yyyy-MM-dd HH:mm") @* <-- Your date format here *@

And then use @Html.PropertyFor(p => p.DateUpdated) in your other views which will automatically use this display template based on the name "DateTime". You can also define other templates like /Views/Shared/DisplayTemplates/DateTimeShort.cshtml:

@model DateTime

@Mode.ToShortDateString()

and use them in your views with @Html.DisplayFor(p => p.DateUpdated, "DateTimeShort")