2012-10-29 13 views
2

在我的MVC應用程序,我有以下ViewModel如何應用自定義的驗證規則給視圖模型屬性在MVC3

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的價值?

回答

1

您可以使用反射來獲取的其他財產作爲this answer(這似乎有點哈克給我),或爲該類創建一個自定義驗證屬性,而不是一個單一的財產討論了here

相關問題