在我的测试应用程序,我有一个日期时间字段定义为这样:日期时间接受超过4个位数的年
[Required(ErrorMessage = "This is required")]
[Display(Name = "test date:")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MMMM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? date1 { get; set; }
在我看来:
@Html.EditorFor(
model => model.date1,
new {
htmlAttributes = new {
@Value = Model.date1 != null ? Model.date1.Value.ToString("yyyy-MM-dd") : ""
}
})
@Html.ValidationMessageFor(model => model.date1, "", new { @class = "text-danger" })
一切工作正常,但是当我进入像10/03/19999(dd,MM,yyyyy)这样的日期,应用程序中断,显然我输入的日期是错误的,但我不知道如何处理错误。我试过使用datetime.tryparse来回传失败,但后来我失去了填充表单的内容。
更新:
继quadzz的解决方案,我已经试过:
[Required(ErrorMessage = "This is required")]
[Display(Name = "test date:")]
[DataType(DataType.Date)]
[Range(typeof(DateTime), "1/1/1900", "31/12/2000", ErrorMessage = "Value for {0} must be between {1} and {2}")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
,但它仍然无法正常工作。
为什么它错了?确定它将会是一个很长的时间,然后才能达到10000但是有一天.. – BugFinder
定义“应用程序中断” – Charleh
“DateTime”支持年份最高达到9999。如果年份多于此值,则认为溢出(并且可能会抛出例外)。你可以创建一个类似'DateTime'的自定义结构,其中包含5位'Year'属性,但似乎需要在结构中声明几个'DateTime'方法。 –