在我的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
的值? 最佳答案
您可以使用反射来获取this answer中的其他属性(在我看来有点不客气),也可以为该类创建自定义验证属性,而不是像here所述的那样创建单个属性。