In ASP.NET MVC 4 Beta, I have an entity with this property:
[DisplayFormat(DataFormatString = "{0:o}", ApplyFormatInEditMode = true)]
public virtual DateTime SavedAt { get; set; }
In a view, generated with the “Controller with read/write actions and views, using EntityFramework” template, I have this code to create an editor for it:
<div class="editor-label">
@Html.LabelFor(model => model.SavedAt)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.SavedAt)
@Html.ValidationMessageFor(model => model.SavedAt)
</div>
Which produces this output:
<div class="editor-label">
<label for="SavedAt">SavedAt</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-date="The field SavedAt must be a date." data-val-required="The SavedAt field is required." id="SavedAt" name="SavedAt" type="text" value="2012-03-31T22:45:18.2244059" />
<span class="field-validation-valid" data-valmsg-for="SavedAt" data-valmsg-replace="true"></span>
</div>
Notice that the date is formatted as “2012-03-31T22:45:18.2244059”.
If I replace the view code fragment with this:
@Html.HiddenFor(model => model.SavedAt)
This code is generated:
<input data-val="true" data-val-date="The field SavedAt must be a date." data-val-required="The SavedAt field is required." id="SavedAt" name="SavedAt" type="hidden" value="31/03/2012 22:45:18" />
Notice that the date is now formatted as “31/03/2012 22:45:18”.
The question is:
Is HiddenFor expected to honor the formatting defined by the DisplayFormat attribute?
If not, what would be a good alternative to have the hidden field output in the desired format?
No, it doesn’t. Only the EditorFor and DisplayFor helpers use the DisplayFormat.
You shouldn’t really care about the format of a hidden field. It’s hidden, nobody sees it. But if for some reason you wanted a custom format you could override the default template with a custom editor template (
~/Views/Shared/EditorTemplates/HiddenInput.cshtml):And then decorate your view model property with the
[HiddenInput]attribute to indicate that you want this to render as a hidden field:And finally: