在 MVC1 中,DataType 属性没有达到您的预期,看起来它在 MVC2 中也没有。你最好的电话是有一个代表日期的字符串属性,在那里检查它的有效性。
这是一个项目的一小段摘录(使用 DataAnnotations 和 xVal):
private List<ErrorInfo> _errors;
private List<ErrorInfo> Errors
{
get
{
if (_errors == null)
_errors = new List<ErrorInfo>();
return _errors;
}
//set { _errors = value; }
}
private string _startDateTimeString;
/// <summary>
/// A string reprsentation of the StartDateTime, used for validation purposes in the views.
/// </summary>
/// <remarks>
/// If the user passes something like 45/45/80 it would be a valid mm/dd/yy format, but an invalid date,
/// which would cause an InvalidOperationException to be thrown by UpdateModel(). By assigning dates to string properties
/// we can check not only the format, but the actual validity of dates.
/// </remarks>
public string StartDateTimeString
{
get
{
return _startDateTimeString;
}
set
{
// Check whether the start date passed from the controller is a valid date.
DateTime startDateTime;
bool validStartDate = DateTime.TryParse(value, out startDateTime);
if (validStartDate)
{
StartDateTime = startDateTime;
}
else
{
Errors.Add(new ErrorInfo("StartDateTime", "Provide a valid date for the start time."));
}
_startDateTimeString = value;
}
}
partial void OnValidate(ChangeAction action)
{
if (action != ChangeAction.Delete)
{
Errors.AddRange(DataAnnotationsValidationRunner.GetErrors(this));
if (StartDateTimeString != null)
{
DateTime startDateTime;
if (!DateTime.TryParse(StartDateTimeString, out startDateTime))
{
Errors.Add(new ErrorInfo("StartDateTime", "Provide a valid date for the start time."));
}
}
if (Errors.Any())
throw new RulesException(Errors);
}
}
}
在我们项目的两个地方都进行检查是有意义的,但我只是想向您展示一个概念。