Reputation: 13960
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);
}
Upvotes: 0
Views: 760
Reputation: 5250
You would have to re-initialize the Courts list, as the entire list is not posted.
Try something like.
[Authorize]
[HttpPost]
public ActionResult Index(CourtSelectionModel courtSelectionModel){
if (!ModelState.IsValid){
IList<Court> courts = new List<Court>();
courts.AddRange(courtBussines.GetCourtsOpenedList());
courtSelectionModel.Courts = Courts;
courtSelectionModel.SelectedCourtId = -1;
return View(courtSelectionModel); //Here, the data to load combobox is null and fails.
}
return RedirectToAction("Horarios", courtSelectionModel);
}
Upvotes: 2