Elbert John Felipe
Elbert John Felipe

Reputation: 181

DropdownList gets no value from Viewbag bind

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

Upvotes: 0

Views: 1190

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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

Upvotes: 1

Related Questions