In my controller, I'm fetching some data to fill a combobox in the view. When data is posted, I check for
ModelState.IsValid
property, if it doesn't, I need to return to the view to show validations messages errors. However, the model only contains the posted data and the other needed to load the combobox is null and it throws a NullReferenceException. Which is the right way to solve this?
public ActionResult Index(){
CourtBussines courtBussines = new CourtBussines();
IList<Court> courts = new List<Court>();
courts.AddRange(courtBussines.GetCourtsOpenedList());
CourtSelectionModel courtSelectionModel = new CourtSelectionModel{Courts = courts, SelectedCourtId = -1};
return View(courtSelectionModel);
}
[Authorize]
[HttpPost]
public ActionResult Index(CourtSelectionModel courtSelectionModel){
if (!ModelState.IsValid){
return View(courtSelectionModel); //Here, the data to load combobox is null and fails.
}
return RedirectToAction("Horarios", courtSelectionModel);
}