在我的 MVC 应用程序中,我有以下内容ViewModel
:
public class MyViewModel
{
public int StartYear { get; set; }
public int? StartMonth { get; set; }
public int? StartDay { get; set; }
public int? EndYear { get; set; }
public int? EndMonth { get; set; }
public int? EndDay { get; set; }
[DateStart]
public DateTime StartDate
{
get
{
return new DateTime(StartYear, StartMonth ?? 1, StartDay ?? 1);
}
}
[DateEnd(DateStartProperty="StartDate")]
public DateTime EndDate
{
get
{
return new DateTime(EndYear ?? DateTime.MaxValue.Year, EndMonth ?? 12, EndDay ?? 31);
}
}
}
我不使用日历助手,因为我需要这种格式的日期(背后有逻辑)。现在我创建了自定义验证规则:
public sealed class DateStartAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
DateTime dateStart = (DateTime)value;
return (dateStart > DateTime.Now);
}
}
public sealed class DateEndAttribute : ValidationAttribute
{
public string DateStartProperty { get; set; }
public override bool IsValid(object value)
{
// Get Value of the DateStart property
string dateStartString = HttpContext.Current.Request[DateStartProperty];
DateTime dateEnd = (DateTime)value;
DateTime dateStart = DateTime.Parse(dateStartString);
// Meeting start time must be before the end time
return dateStart < dateEnd;
}
}
问题是DateStartProperty
(在这种情况下StartDate
)不在Request
对象中,因为它是在表单发布到服务器之后计算的。因此dateStartString
始终为空。我怎样才能得到 的价值StartDate
?