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

后端 未结 1 1295
野趣味
野趣味 2020-11-27 23:35

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

相关标签:
1条回答
  • 2020-11-28 00:07

    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.

    0 讨论(0)
提交回复
热议问题