0

I've looked at many other stack overflow questions with people reporting this question but none of them managed to help. But I'm getting the error only when I try to apply some sort of validation to the models attributes and when I attempt to enforce that validition (e.g put return date before departure date). If I choose the correct value it works.

public int Id { get; set; }
    [Required(ErrorMessage = "-Select-")]
    public string Departure { get; set; }

    [Required(ErrorMessage = "-Select-")]
    public string Arrivals { get; set; }

    [Required(ErrorMessage = "Date Expected!")]
    [DataType(DataType.Date)]
    public System.DateTime DepartureDate { get; set; }

    [Required(ErrorMessage = "Date Expected!")]
    [DataType(DataType.Date)]
    [GreaterThan("DepartureDate", ErrorMessage="Retrun date must be after departure date!")]
    public System.DateTime ReturnDate { get; set; }

The view:

<p>From: </p>
@Html.DropDownList("Departures", ViewData["departures"] as List<SelectListItem>);
@Html.ValidationMessageFor(model => model.Departure, "Please choose a location");
<p>To: </p>
@Html.DropDownList("Arrivals", ViewData["arrivals"] as List<SelectListItem>);
@Html.ValidationMessageFor(model => model.Arrivals, "Please choose a location");

(Select list is initialized in my controller)

 Departures.Add(new SelectListItem { Text = "Bristol", Value = "Bristol" });
 ViewData["departures"] = Departures;

There is a lot more .Add's and this is also repeated for arrivals

        [HttpGet]
    public ActionResult BookFlight()
    {
        // Check if the user is logged in, if not redirect to log in page
        if (User.Identity.IsAuthenticated)
        {
            Departures.Add(new SelectListItem { Text="-Select-", Value="0" });
            Departures.Add(new SelectListItem { Text = "London", Value = "London" });
            Departures.Add(new SelectListItem { Text = "Manchester", Value = "Manchester" });
            Departures.Add(new SelectListItem { Text = "Edinburgh", Value = "Edinburgh" });
            Departures.Add(new SelectListItem { Text = "East Midlands", Value = "East Midlands" });
            Departures.Add(new SelectListItem { Text = "Bristol", Value = "Bristol" });
            ViewData["departures"] = Departures;

            Arrivals.Add(new SelectListItem { Text = "-Select-  ", Value = "0" });
            Arrivals.Add(new SelectListItem { Text = "Paris", Value = "Paris" });
            Arrivals.Add(new SelectListItem { Text = "Barcelona", Value = "Barcelona" });
            Arrivals.Add(new SelectListItem { Text = "Madrid", Value = "Madrid" });
            Arrivals.Add(new SelectListItem { Text = "Amsterdam", Value = "Amsterdam" });
            Arrivals.Add(new SelectListItem { Text = "Prague", Value = "Prague" });
            Arrivals.Add(new SelectListItem { Text = "Nice", Value = "Nice" });
            Arrivals.Add(new SelectListItem { Text = "Milan", Value = "Milan" });
            Arrivals.Add(new SelectListItem { Text = "Geneva", Value = "Geneva" });
            Arrivals.Add(new SelectListItem { Text = "Rome", Value = "Rome" });
            ViewData["arrivals"] = Arrivals;

            return View();

        }
        else
            return RedirectToAction("../User/LogIn");
    }

    [HttpPost]
    public ActionResult BookFlight(FlightDetailsMD flights, FormCollection form)
    {
        Random rand = new Random();
        Random rand2 = new Random();
        if (ModelState.IsValid) 
        {
            var departureVal = form["departures"];
            var arrivalVal = form["arrivals"];
            using (var db = new FlightDetailsEntities()) 
            {
                var user = db.FlightDetails.Create();

                user.Id = rand.Next(100000, 199999) + rand2.Next(100000, 199999);
                user.Departure = departureVal;
                user.Arrivals = arrivalVal;
                user.DepartureDate = flights.DepartureDate;
                user.ReturnDate = flights.ReturnDate;

                db.FlightDetails.Add(user);
                db.SaveChanges();

                MailMessage mail = new MailMessage();
                mail.To.Add(User.Identity.Name);
                mail.From = new MailAddress(User.Identity.Name);
                mail.Subject = "Booking Confirmation";
                string Body = "Email from: <i>insert company name</i><br><br> Your booking is confirmed! You are going to " + user.Arrivals +
                    " on " + string.Format("{0:dd/MM/yyyy}", user.DepartureDate) + " and returning to " + user.Departure + " on " + string.Format("{0:dd/MM/yyyy}", user.ReturnDate) +
                    ".<br> Thank you for booking with us and we hope you have a nice time!" + "<br><h2>Reference #" + user.Id + "</h2>";
                mail.Body = Body;
                mail.IsBodyHtml = true;
                //SmtpClient client = new SmtpClient();
                using (SmtpClient client = new SmtpClient())
                {
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(User.Identity.Name, "RecurveBow");
                    client.Host = "smtp.live.com";
                    client.Port = 587;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.Send(mail);
                }
                  /*
                    ViewData["departures"] = Departures;
                    ViewData["arrivals"] = Arrivals;
                */

                /*
                    ViewData["departures"] = " ";
                    ViewData["arrivals"] = " ";
                */

                return RedirectToAction("BookingDetails", "Home");
            }
        }

        return View();
    }
DJLad97
  • 195
  • 1
  • 10
  • Can you show us the GET and POST actions, specifically where you set ViewData["departures"] and ViewData["arrivals"] ? – emre nevayeshirazi Apr 10 '16 at 16:30
  • Updated my question the code you requested :) – DJLad97 Apr 10 '16 at 17:36
  • 1
    You should reset the values of ViewData["departures"] and ViewData["arrivals"] just before return View(); in POST action. They are not posted back to your POST action, therefore, when the validation fails and you view engine tried to render your .cshtml page, it cannot find the ViewData["departures"] and ViewData["arrivals"]. If it works let me know :) – emre nevayeshirazi Apr 10 '16 at 17:40
  • Did you mean either of the piece of code in the comments that I've just put in? – DJLad97 Apr 10 '16 at 19:59
  • Saif's answer was what i meant. – emre nevayeshirazi Apr 10 '16 at 21:25
  • Different error message because you use `DropDownList` rather that DropDownListFor, but otherwise identical to the duplicate (you do not reassign the SelectList's when you return the view in the POST method –  Apr 10 '16 at 21:40
  • Yep that worked, thank you :) – DJLad97 Apr 11 '16 at 15:51

1 Answers1

0

made some changes. check it out :).

[HttpGet]
    public ActionResult BookFlight()
    {
        // Check if the user is logged in, if not redirect to log in page
        if (User.Identity.IsAuthenticated)
        {
            SetDepartureandArrival();
            return View();

        }
        else
            return RedirectToAction("../User/LogIn");
    }
    public void SetDepartureandArrival()
    {
            Departures.Add(new SelectListItem { Text = "-Select-", Value = "0" });
            Departures.Add(new SelectListItem { Text = "London", Value = "London" });
            Departures.Add(new SelectListItem { Text = "Manchester", Value = "Manchester" });
            Departures.Add(new SelectListItem { Text = "Edinburgh", Value = "Edinburgh" });
            Departures.Add(new SelectListItem { Text = "East Midlands", Value = "East Midlands" });
            Departures.Add(new SelectListItem { Text = "Bristol", Value = "Bristol" });
            ViewData["departures"] = Departures;

        Arrivals.Add(new SelectListItem { Text = "-Select-  ", Value = "0" });
        Arrivals.Add(new SelectListItem { Text = "Paris", Value = "Paris" });
        Arrivals.Add(new SelectListItem { Text = "Barcelona", Value = "Barcelona" });
        Arrivals.Add(new SelectListItem { Text = "Madrid", Value = "Madrid" });
        Arrivals.Add(new SelectListItem { Text = "Amsterdam", Value = "Amsterdam" });
        Arrivals.Add(new SelectListItem { Text = "Prague", Value = "Prague" });
        Arrivals.Add(new SelectListItem { Text = "Nice", Value = "Nice" });
        Arrivals.Add(new SelectListItem { Text = "Milan", Value = "Milan" });
        Arrivals.Add(new SelectListItem { Text = "Geneva", Value = "Geneva" });
        Arrivals.Add(new SelectListItem { Text = "Rome", Value = "Rome" });
        ViewData["arrivals"] = Arrivals;
    }
    [HttpPost]
    public ActionResult BookFlight(FlightDetailsMD flights, FormCollection form)
    {
        Random rand = new Random();
        Random rand2 = new Random();
        if (ModelState.IsValid)
        {
            var departureVal = form["departures"];
            var arrivalVal = form["arrivals"];
            using (var db = new FlightDetailsEntities())
            {
                var user = db.FlightDetails.Create();

                user.Id = rand.Next(100000, 199999) + rand2.Next(100000, 199999);
                user.Departure = departureVal;
                user.Arrivals = arrivalVal;
                user.DepartureDate = flights.DepartureDate;
                user.ReturnDate = flights.ReturnDate;

                db.FlightDetails.Add(user);
                db.SaveChanges();

                MailMessage mail = new MailMessage();
                mail.To.Add(User.Identity.Name);
                mail.From = new MailAddress(User.Identity.Name);
                mail.Subject = "Booking Confirmation";
                string Body = "Email from: <i>insert company name</i><br><br> Your booking is confirmed! You are going to " + user.Arrivals +
                    " on " + string.Format("{0:dd/MM/yyyy}", user.DepartureDate) + " and returning to " + user.Departure + " on " + string.Format("{0:dd/MM/yyyy}", user.ReturnDate) +
                    ".<br> Thank you for booking with us and we hope you have a nice time!" + "<br><h2>Reference #" + user.Id + "</h2>";
                mail.Body = Body;
                mail.IsBodyHtml = true;
                //SmtpClient client = new SmtpClient();
                using (SmtpClient client = new SmtpClient())
                {
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(User.Identity.Name, "RecurveBow");
                    client.Host = "smtp.live.com";
                    client.Port = 587;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.Send(mail);
                }


                return RedirectToAction("BookingDetails", "Home");
            }
        }
         SetDepartureandArrival();
        return View();
    }
saif iqbal
  • 219
  • 1
  • 9