There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'DoctorId

Viewed 35

I am trying to validate dropdownlist like if the user has not selected any options display error message. But while inserting without selecting any options I am facing issues regarding-- There is no ViewData item of type 'IEnumerable' that has the key 'DoctorId.I want nothing is selected and user press add button then display error message.I am new to MVC so I found it difficult. If anyone has ideas please share.

My model class

 [Required]
public Nullable<decimal> DoctorId { get; set; }

Controller

 public ActionResult InsertPatients()
        {
            var doctlist = db.Doctors.ToList();
            ViewBag.DoctorId = new SelectList(doctlist, "DoctorId", "DoctorName");
            return View();
        }
      [HttpPost]
        public ActionResult InsertPatients(Patient NewRec)
        {
            if (ModelState.IsValid)
            {
                
                try
                {
                    var res = ServiceClient.PostAsJsonAsync<Patient>("InsertPatient", NewRec).Result;
        if (res.IsSuccessStatusCode)
                    {

                      return RedirectToAction("ShowPatients");
               }
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            System.Console.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        }
                    }
                }
            }
            return View();

        }

DropdownList

 @Html.DropDownListFor(model => model.DoctorId, ViewBag.DoctorId as IEnumerable<SelectListItem>, "Select Doctor")

Thanks in advance

1 Answers

The Viewbag should write in this way.

 ViewBag.DoctorId = new SelectList((from s in db.Doctors 
                                      select new {Id = s.DoctorId, Name = s.DoctorName}), "Id", "Name ");

The view should look this. Just put required = true to validate.

@Html.DropDownListFor(model => model.DoctorId, (SelectList)ViewBag.DoctorId , "Select Doctor",new {Required = true})

one more thing, the viewbag also need to include in your post action. Here, you can include the doctorId as default value.

 ViewBag.DoctorId = new SelectList((from s in db.Doctors 
                                          select new {Id = s.DoctorId, Name = s.DoctorName}), "Id", "Name ",NewRec.DoctorId);

If the action fail. You should pass back the model to the view so the user does not need to retype everything. Under the view, you can pass back the model

return View(NewRec);
Related