How to set the DisplayFormatString property on ModelMetadata object in razor-engine?

920 Views Asked by At

I have an Asp.Net MVC 5 project. I am trying to utilize the DisplayTemplates to make my view more dynamic.

I am trying to create a display-template for any DateTime property. But I am unable to set ViewData.ModelMetadata.DisplayFormatString property for some reason.

Here is how my view-model looks like

public class DisplayClientViewModel : IMapFrom
{
    public int Id { get; set; }
    public string Name { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime? EnrolledAt { get; set; }
}

Here is my DateTime.cshtml view

@model DateTime?

@if (!Model.HasValue && ViewData.ModelMetadata.NullDisplayText != null)
{
    <span>@ViewData.ModelMetadata.NullDisplayText</span>
}
else if (Model.HasValue)
{
    <span>@Model.Value.ToString(ViewData.ModelMetadata.DisplayFormatString ?? "g")</span>
}

Since my EnrolledAt property is decorated with [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] I am expecting the ViewData.ModelMetadata.DisplayFormatString to be set to {0:MM/dd/yyyy} But it is always set to null for some reason.

How can I either set the ViewData.ModelMetadata.DisplayFormatString property on the ModelMetadata from the view-model, or access the value on DisplayFormat.DataFormatString?

Note: I am aware that I could decorate the property with [DataType(DataType.Data)] and create a Date.cshtmltemplate that would just display the short date. But in this case, I am hoping to be able to handle any format, not just Date or Time.

0

There are 0 best solutions below