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