In my MVC application I have the following 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);
}
}
}
I do not use a calendar helper because I need the date in this format (there is a logic behind). Now I created my Custom Validation rule:
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;
}
}
The problem is that DateStartProperty (in this case StartDate) is not in the Request object since it is calculated after the form is posted to the server. Therefore the dateStartString is always null. How can I get the value of StartDate?