ASP.net MVC Data Annotations DateTime Default Value

℡╲_俬逩灬. 提交于 2019-12-01 16:25:35

问题


In my view model i have the following attribute:

 [Required]
 [DataType(DataType.Date, ErrorMessage="Please enter a valid date in the format dd/mm/yyyy")]
 [Display(Name = "Date of Birth")]
 public DateTime DOB { get; set; }

In my view i have the following:

<div class="editor-label">
    @Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.DOB)
    @Html.ValidationMessageFor(model => model.DOB)
</div>

Before submitting the form the default value for DOB is 1/01/0001 how do i stop this value being auto populated, i simply want an empty field when people visit this form?


回答1:


I believe you will have to use the nullable DateTime? type. DateTime cannot be null thus it will always have a value.




回答2:


Try making the DOB DateTime nullable like @Mayo states:

public DateTime? DOB { get; set; }



回答3:


DateTime is of type struct. So, by default DateTime cannot be null. It has default value equal to '01/01/0001'. Solution to your problem is to use the nullable DateTime? type. If you want it to default to some value like '01/01/2014', then you can assign value like: DOB = new DateTime(2014, 01, 01);



来源:https://stackoverflow.com/questions/4351969/asp-net-mvc-data-annotations-datetime-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!