Value cannot be null. Parameter name: items (DrodownList)

被刻印的时光 ゝ 提交于 2019-11-26 21:03:52

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!