Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 471
Adam O'Brien Avatar asked Dec 04 '10 04:12

Adam O'Brien


People also ask

What is the default value for DateTime?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.

Can DateTime be null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

What is default C#?

A default value expression produces the default value of a type. There are two kinds of default value expressions: the default operator call and a default literal. You also use the default keyword as the default case label within a switch statement.


2 Answers

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

like image 184
Mayo Avatar answered Oct 13 '22 01:10

Mayo


Try making the DOB DateTime nullable like @Mayo states:

public DateTime? DOB { get; set; }
like image 39
amurra Avatar answered Oct 13 '22 01:10

amurra