简体   繁体   English

ASP.net MVC数据注释DateTime默认值

[英]ASP.net MVC Data Annotations DateTime Default Value

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? 在提交表单之前,DOB的默认值是1/01/0001如何停止自动填充此值,我只想在人们访问此表单时使用空字段?

I believe you will have to use the nullable DateTime? 我相信你将不得不使用可以为空的DateTime? type. 类型。 DateTime cannot be null thus it will always have a value. DateTime不能为null,因此它始终具有值。

尝试使DOB DateTime像@Mayo状态一样可以为空:

public DateTime? DOB { get; set; }

DateTime is of type struct. DateTime的类型为struct。 So, by default DateTime cannot be null. 因此,默认情况下DateTime不能为null。 It has default value equal to '01/01/0001'. 它的默认值等于'01 / 01/0001'。 Solution to your problem is to use the nullable DateTime? 您的问题的解决方案是使用可空的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); 如果您希望它默认为某个值,如'01 / 01/2014',那么您可以指定如下值:DOB = new DateTime(2014,01,01);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM