I’m trying to create an Editor Template for a DateTime field and it does not seem to respect my DisplayFormat attribute.
My model:
public class Project
{
[Display(Name="Project Name")]
[Required]
public string ProjectName { get; set; }
[Display(Name="Start Date")]
[DisplayFormat(DataFormatString="{0:M/d/yyyy}", ApplyFormatInEditMode=true)]
public DateTime? StartDate { get; set; }
}
My Editor Template in folder /Views/Projects/EditorTemplates/DateTime.cshtml
@model DateTime?
@Html.TextBoxFor(m => Model, new { @class="datepicker" })
Here is the View that ties everything together:
@model Project
<fieldset>
<legend>Project</legend>
<div class="editor-label">
@Html.LabelFor(m => m.ProjectName)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.ProjectName)
@Html.ValidationMessageFor(m => m.ProjectName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.StartDate)
</div>
<div class="editor-field">
@Html.EditorFor(m => m.StartDate)
@Html.ValidationMessageFor(m => m.StartDate)
</div>
</fieldset>
When I have it this way then I am seeing the time portion of the date. When I remove the editor template then it works fine and only shows the date portion. Why does it seem to ignore DisplayFormat when I have an Editor Template?
Let’s first look at what happens when you don’t use a template. I have added the generic type to make it even more explicit what the difference is.
Now let’s look at your template editor:
Notice the difference? In the latter case you are simply dealing with a DateTime instance, which means that you are losing the metadata defined by the model’s property.
By using a template you are the one responsible for handling the metadata, which should be provided to your template in
ViewData.ModelMetadata.*. For example in your case you will need to format the date yourself usingViewData.ModelMetadata.DisplayFormatString