0

I have dropdownlists populated from my controller and passed in the view through viewbags. The binding seems okay until I submit the form and gets null value. But when I put the codes in the view itself, it works. Am I missing a cast?

a snippet of my dropdownlist for "Year":

@Html.DropDownListFor(model => model.Year, new SelectList(ViewBag.Year, "Value", "Text"), htmlAttributes: new { @class = "form-control"})

Whereas the ViewBag.Year data is from my controller that has the ff codes:\

List<SelectListItem> year = new List<SelectListItem>();

                for (var i = 1990; i <= DateTime.Now.Year; i++)
            {
                year.Add(new SelectListItem
                {
                    Text = i.ToString(),
                    Value = i.ToString(),
                    Selected = false
                });
            }

ViewBag.Year = year;

the error I get:

enter image description here

DeanOC
  • 7,142
  • 6
  • 42
  • 56

1 Answers1

1

Consider a case when user submitting the form and validation mechanism fails (returning same view), ViewBag.Year has null value when passed to DropDownListFor (since it's not repopulated after POST request) and throws ArgumentNullException.

To solve this issue, simply repopulate ViewBag.Year when returning the same view in POST method, by replicating how to populate ViewBag.Year in GET method like this example:

[HttpPost]
public ActionResult SubmitForm(FormModel model)
{
    if (ModelState.IsValid)
    {
        // other stuff
    }

    List<SelectListItem> year = new List<SelectListItem>();

    for (var i = 1990; i <= DateTime.Now.Year; i++)
    {
        year.Add(new SelectListItem
        {
            Text = i.ToString(),
            Value = i.ToString(),
            Selected = false
        });
    }

    ViewBag.Year = year; // this line repopulates ViewBag when submit failed

    return View(model);
}

Similar issues:

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

Value cannot be null. Parameter name: items (in Dropdown List) ASP.NET MVC5

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • oh I have to rewrite the code. hmm seems inefficient. I guess I'll try to separate the population in an independent method that returns a list then call it whenever I need it. – Elbert John Felipe Jul 03 '17 at 03:23
  • It is true that I prefer creating an independent method which populates `ViewBag.Year` and call the method on both GET & POST method there. I had explained what's wrong: the `ViewBag` is not repopulated while POST method returns same view. – Tetsuya Yamamoto Jul 03 '17 at 03:29
  • I can't set the default value in this case of populating the list programatically – Elbert John Felipe Jul 04 '17 at 04:41