Respecting DisplayFormat in custom DateTime template

430 Views Asked by At

I would like to create a custom template for displaying properties of the type DateTime while still being able to define the format using the DisplayFormat decoration in the class.

Let's say I want to surround every date with >> and << using a template.
This would be the class:

public class Item
{
    public virtual Guid Id { get; set; }

    [UIHint("MyDateTimeTemplate")]
    [DisplayFormat(DataFormatString = "{0:dd.MM.yyyy mm:hh}")] //no seconds
    public virtual DateTime CreatedOn { get; set; }
}

But using >>@Model<< as the MyDateTimeTemplate.cshtml template doesn't respect the DataFormatString.

I also tried >>@Html.DisplayFor(x => Model)<<, but this doesn't output anything (maybe due to a recursion loop because the template calls itself instead of the default?)

2

There are 2 best solutions below

1
On BEST ANSWER

Something like

MyDateTimeTemplate.cshtml

<div>
  <span>>></span>
  <span>@string.Format(ViewData.ModelMetadata.DisplayFormatString, Model)</span>
  <span><<</span>
</div>
0
On

This is only a workaround, but if the template only consists of ">>@Model<<" maybe you want to create a HtmlHelper instead. Get @Html.DisplayFor in the helper method's body and then wrap that in >> <<. Something like this (haven't checked if the code works but hopefully gets you started):

    public static MvcHtmlString DisplayWrappedDateFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, DateTime>> expression)
    {
        var originalDisplay = html.DisplayFor(expression).ToHtmlString();
        var newDisplay = String.Format("&gt;&gt;{0}&lt;&lt;", originalDisplay)

        return MvcHtmlString.Create(newDisplay);
    }