C# 最终解决:字段必须是日期
问题: 我需要捕获日期和时间数据,并在我的模型类中编写了以下内容:C# 最终解决:字段必须是日期,c#,jquery,date,validation,datepicker,C#,Jquery,Date,Validation,Datepicker,问题: 我需要捕获日期和时间数据,并在我的模型类中编写了以下内容: [Required(ErrorMessage = "Date of Birth cannot be empty")] [Display(Name = "Date of Birth")] public DateTime DateofBirth{ get; set; } [Required(ErrorMessage = "Date of Birth cannot be empty")] [Display(Name = "Date
[Required(ErrorMessage = "Date of Birth cannot be empty")]
[Display(Name = "Date of Birth")]
public DateTime DateofBirth{ get; set; }
[Required(ErrorMessage = "Date of Birth cannot be empty")]
[Display(Name = "Date of Birth")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0:dd MMMM yyyy}")]
public DateTime DateofBirth{ get; set; }
我有一个日期选择器设置:
$('#DateofBirth').datepicker({
dateFormat: "dd MM yy",
changeMonth: true,
changeYear: true,
autoclose: true,
});
当我选择日期时,文本框验证总是说:“字段出生日期必须是日期”。
即使我不使用datepicker(我手动写入日期),它也会一直这样说
我认为这与javascript或jquery有关,因为我从提供的许多解决方案中看到了这一点。但是,验证一直在说“字段出生日期必须是一个日期”
在没有好结果的搜索之后,我终于意识到ASP.NET使用的日期时间格式与jQuery使用的日期时间格式不同。
如前所述,日期和时间的常规DataFormatString是6/15/2009 1:45:30 PM,因此如果我没有完全按照该格式编写,验证错误就会弹出。甚至,当我使用datepicker填充文本框时。解决方案: 基于和,我必须匹配ASP.NET模型和jQuery datepicker的日期时间 因此,我在模型类中编写自定义日期-时间格式为dd-MMMM-yyyy:
[Required(ErrorMessage = "Date of Birth cannot be empty")]
[Display(Name = "Date of Birth")]
public DateTime DateofBirth{ get; set; }
[Required(ErrorMessage = "Date of Birth cannot be empty")]
[Display(Name = "Date of Birth")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0:dd MMMM yyyy}")]
public DateTime DateofBirth{ get; set; }
在jQuery datepicker属性中,日期时间格式为dd-MM-yy,如下所示
$('#DateofBirth').datepicker({
dateFormat: "dd MM yy",
changeMonth: true,
changeYear: true,
autoclose: true,
});
我希望它能有所帮助。如果你想发布解决方案,请将其写在答案中,而不是问题中。好的,谢谢你的建议。