Display empty editor for default values ​​using editor

My model has the property:

[Required] [DataType(DataType.Date)] public DateTime BirthDate { get; set; } 

which I show 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 text field of the date of birth shows "01.01.0001", that is, the default value is DateTime. This is correct if the BirthDate is not initialized, however I want the text box to be empty in this case.

What is the standard way to do this? I do not want to use Nullable <DateTime> in my model because BirthDate is a required value.

+4
source share
1 answer

You are looking rather for DisplayFormat . Also, if you are not using DateTime? / Nullable<DateTime> , you are likely to end on January 1 (since there cannot be a null value).

Should you decide to use DateTime? / Nullable<DateTime> forcing the value using [Required] , you should avoid any problems you are talking about, so if this were your uncertainty, I would not worry too much.

As a final alternative, you can override DateTime.cshtml (or Date.cshtml since you are using the DataType attribtue template) (~ / Views / Shared / DisplayTemplates /) and make the text field empty when filling in default(DateTime) . eg.

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

(or something like that)

+2
source

Source: https://habr.com/ru/post/1491648/


All Articles