2017-06-29 103 views
-3

我想爲日期時間字段創建自定義驗證。自定義驗證日期c#

有我的課的預訂,同場 「日期」 上,我想把驗證:

public class Booking 
    { 
     public int Id { get; set; } 
     public int Restochoisi { get; set; } 
     public int Nbpeople { get; set; } 
     [CustomValidator] 
     public DateTime Date { get; set; } 
     public int Orga { get; set; } 
    } 

類CustomValidator.cs:

[AttributeUsage(AttributeTargets.Property | 
    AttributeTargets.Field, AllowMultiple = false)] 
public class CustomValidator : ValidationAttribute 
{ 
    protected override bool IsValid(object value) 
    { 
     if ((DateTime)value < DateTime.Now) 
      return false; 
     return true; 
    } 

} 

和BookingController:

[HttpPost] 
    public ActionResult Index(int restochoisi, int nbpeople, DateTime start, int orga) 

    { 
     var context = new BddContexte(); 

     var vm = new BookingViewModel() 
     { 
      Restos = new SelectList(context.Restos.AsEnumerable(), "Id", "Nom"), 
      Utilisateurs = new SelectList(context.Utilisateurs.AsEnumerable(), "Id", "Prenom") 

     }; 

     //ViewBag.result = restochoisi + " " + nbpeople + " " + datepicker + " " + orga; 
     //dal.RestoById(restochoisi) 
     if (ModelState.IsValid) 
     { 
      int id = dal.CreerBooking(restochoisi, nbpeople, start, orga); 
      return View(vm); 
     } 
     return View(vm); 
    } 

但它不起作用。我的步態有什麼問題嗎?

+2

究竟什麼是行不通的?你有錯誤嗎?沒有錯誤? – Mederic

+0

當我輸入一個「錯誤的」日期時,我的函數「CreerBooking」中出現錯誤。 –

回答

0

你的控制器應該用你的模型類的驗證

[HttpPost] 
public ActionResult Index(Booking booking) 
{ 
    // snip 
} 

不這樣做,我不知道你是怎麼想的自定義驗證將工作?

+0

通過此修改,我沒有任何錯誤,但即使日期正確,模型狀態始終爲false –

+0

@MatthieuVeron - ModelState會告訴您什麼對您的模型無效。修理它。 – Jamiec

+0

?? 這正是我的問題的目的。我不明白我的代碼中有什麼不正確,並且這使得modelstate不返回我希望返回的結果 –