在我的 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 .
关于c# - 如何将自定义验证规则应用于 MVC3 中的 ViewModel 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13118639/