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.
Best Answer
You're looking for the
DisplayFormat
attribute most likely. Also, unless you're using aDateTime?
/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
(orDate.cshtml
since you're using theDataType
attribtue) template (~/Views/Shared/DisplayTemplates/) and make the textbox empty when populated withdefault(DateTime)
. e.g.(Or something along those lines)