asp.netasp.net-mvcasp.net-mvc-3datatemplatedisplayformat

Respecting DisplayFormat in custom DateTime template


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?)


Solution

  • Something like

    MyDateTimeTemplate.cshtml

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