I'm trying to return a list of emails from a model using DropDownListFor. I have found a few topics on this issue, so it seems to be common, and I presume the list needs to be repopulated, but I can't find a way that works (or a way that I understand against the other examples).
I always get the null error regardless of what I do. I'm thinking that maybe actually it is not returning any emails in the first place, but I'm not understanding the way dropdownlist works with a model.
Is there a different issue causing the null that I can't see right now?
I define the list in a class:
public class User {
[Required]
[Display(Name = "Email Address")]
public string Email { get; set; }
public IEnumerable<SelectListItem> EmailList { get; set; }
}
Controller:
[HttpGet]
public ActionResult ChangeDetails()
{
var u = new User();
ViewBag.DropDownList = new SelectList(u.EmailList, "Email", "Email");
return View(u);
}
View:
@Html.DropDownListFor(model => model.Email, (IEnumerable<SelectListItem>)ViewBag.DropDownList, "---Select a value---", new { htmlAttributes = new { @class = "form-control" } })
Error message:
Message: Value cannot be null. Parameter name: items
at System.Web.Mvc.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, String dataGroupField, IEnumerable selectedValues, IEnumerable disabledValues, IEnumerable disabledGroups) ....
new SelectList... trial and error really. Edited the main post to add the ViewBag in razor.u.EmailListisnull(you did not initialize it, let alone populate it with any items)lst) below in a foreach and doingSelectListItem item in user.EmailList, but to no avail. I feel like I'm not understanding something.var u = new User();which just initializes a newUserwhich wont have any items. And you do not even needViewBag.DropDownList = ...The model already contains a propertyIEnumerable<SelectListItem> EmailListso in the view its just@Html.DropDownListFor(model => model.Email, Model.EmailList, "---Select a value---", new { ... })(except that you must first initializeEmailListso its notnull)