Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date field giving required error on validation

I have created a model in my asp.net MVC 3 website and have a property named DateOpened:

  [Column("Date Opened")]
        [Display(Name = "Date Opened:")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
        public DateTime DateOpened { get; set; }

I didn't apply [Required] data annotation to it, but when I try to save the form, It says required field. In database it is null.

Please suggest solution.

like image 817
DotnetSparrow Avatar asked Feb 11 '12 10:02

DotnetSparrow


1 Answers

That's normal. DateTime is a value type meaning that it will always require a value. The model metadata provider in ASP.NET MVC automatically adds the required attribute to non-nullable data types. You could use a nullable DateTime:

[Column("Date Opened")]
[Display(Name = "Date Opened:")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? DateOpened { get; set; }
like image 199
Darin Dimitrov Avatar answered Oct 22 '22 18:10

Darin Dimitrov