Date field giving required error on validation

限于喜欢 提交于 2019-12-01 00:45:40

问题


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.


回答1:


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; }


来源:https://stackoverflow.com/questions/9239451/date-field-giving-required-error-on-validation

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