Display empty editor for default values using EditorFor

asp.net-mvc-4

Solution

You're looking for the `DisplayFormat` attribute most likely. Also, unless you're using a `DateTime?`/`Nullable<DateTime>` you're probably going to end up with Jan 1 (since there can't be a null value).

If you do decide to use `DateTime?`/`Nullable<DateTime>` enforcing a value using `[Required]` should avoid any issues you're speaking of, so if that was your hesitation I wouldn't be too worried.

As a final alternative, you can override the `DateTime.cshtml` (or `Date.cshtml` since you're using the `DataType` attribtue) template (~/Views/Shared/DisplayTemplates/) and make the textbox empty when populated with `default(DateTime)`. e.g.

@model DateTime
@Html.TextBox(String.Empty, Model == default(DateTime) ? String.Empty : Model)

(Or something along those lines)

Problem

My model has a property: ``` [Required] [DataType(DataType.Date)] public DateTime BirthDate { get; set; } ``` which I'm displaying in my (strongly typed) view using EditorFor: ``` <p>@Html.LabelFor(m => m.BirthDate) @Html.EditorFor(m => m.BirthDate) @Html.ValidationMessageFor(m => m.BirthDate) </p> ``` When the view is rendered the birth date textbox shows "01.01.0001", i.e. the DateTime default value. This is correct if the BirthDate value is not initialized, however I want the textbox to be empty in that case. What is the standard way to do this? I don't want to use Nullable<DateTime> in my model because BirthDate is a required value.

Original source