I\'m working with ASP.NET MVC4 and now I want to add a dropdownlist with data from my mysql database. This is what I do :
In my view (Register.cshtm
Consider the case when model validation fails. View will be redisplayed again with model sent with the request. However this line:
new SelectList(ViewBag.Districts, "district_id", "district_name", Model.Districts)
will have null
as a first parameter, since ViewBag.Districts
was not repopulated, causing the exception. So in order to avoid exception just set this property again:
// If we got this far, something failed, redisplay form
var districts = repository.GetDistricts();
ViewBag.Districts = districts;
return View(model);
Update. When seeing the model definition, thing that immediately comes into the mind is Required
attribute of the Districts
collection. Most likely you do not need user to enter any of those, nor you save them into the database. Try removing this attribute, and error about this property will disappear.