0

Possible Duplicate:
MVC3 custom validation: compare two dates

I am trying to make a validation for my date so that start date must be < than end date.If end date is before start date tha n i throw an exception .How can i show this exception on my screen so when i press search buton and the dates are wrong a message to appear?

    public ActionResult SearchFree(DateTime? StartDate, DateTime? EndDate)
    {

        if (StartDate.HasValue && EndDate.HasValue)
        {
        DateTime d1 = StartDate.Value;
        DateTime d2 = EndDate.Value;
        TimeSpan span = d2 - d1;


        if (span.Days <= 0)
        {
            throw new ArgumentOutOfRangeException("start date must be before end date");
        }

        try
        {
            DBContext.Current.Open();
            var model = Reservation.SelectFreeRooms(StartDate, EndDate);
            DBContext.Current.Close();
            return View(model);
        }
        catch (ArgumentException ae)
        {
            throw ae;
        }


              }
      return View(new List<dynamic>());
    }

enter image description here

Community
  • 1
  • 1
jonny
  • 797
  • 4
  • 24
  • 41
  • you really don't want to throw an exception here. you should return your view and pass it the validation message. – c0deNinja Jun 21 '12 at 20:09
  • you better use ModelState.AddModelError() to return the same view-model with validation error. For client side validation you may use js or jquery scripting. – Yusubov Jun 21 '12 at 20:34

1 Answers1

4
public ActionResult SearchFree(DateTime? StartDate, DateTime? EndDate)
{

    if (!StartDate.HasValue || !EndDate.HasValue)
    {
        ModelState.AddModelError("Date", "Dates are empty");
        return View();
    }

    if(StartDate.Value > EndDate.HasValue
    {
        ModelState.AddModelError("Date", "start date must be before end date");
        return View();
    }

    try
    {
        DBContext.Current.Open();
        var model = Reservation.SelectFreeRooms(StartDate, EndDate);
        DBContext.Current.Close();
        return View(model);
    }
    catch ()
    {
        ModelState.AddModelError("", "Db problem");
        return View();
    }
}

But the best way - using some model and validate it using attributes

Bohdan
  • 1,984
  • 3
  • 20
  • 27