kamil1995b
kamil1995b

Reputation: 121

Value cannot be null. Parameter name: items on DropDownListFor

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) ....

Upvotes: 0

Views: 8359

Answers (2)

rikobgrff
rikobgrff

Reputation: 19

ensure that you are passing your selectlist in both get and post methods

Upvotes: 0

Willy David Jr
Willy David Jr

Reputation: 9171

Try this as SelectListItem:

IList<SelectListItem> lst = new List<SelectListItem>();
        lst.Add(new SelectListItem()
            {
               Value = "Hello",
                Text = "World"
            });        
ViewBag.DropDownList = lst;

Or:

var u = new User();
ViewBag.DropDownList = u.EmailList //You need to populate your EmailList first before you declare it here.
return View(u);

Another option is this:

IList<SelectListItem> lst = new List<SelectListItem>();
        lst.Add(new SelectListItem()
            {
               Value = "Email",
               Text = "Email"
            });            
ViewBag.DropDownList = new SelectList(p.EmailList, "Value", "Text");

and on your View:

@Html.DropDownListFor(model => model.Email, (SelectList)ViewBag.DropDownList, "---Select a value---", new { htmlAttributes = new { @class = "form-control" } })

Upvotes: 3

Related Questions