DropdownList没有从Viewbag绑定中获取任何值

时间:2017-07-03 02:15:49

标签: c# asp.net-mvc-5

我有从我的控制器填充的下拉列表,并通过viewbags传递到视图中。绑定似乎没问题,直到我提交表单并获得null值。但是当我把代码放在视图中时,它就可以了。我错过了演员吗?

我的“年份”下拉列表的片段:

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

而ViewBag.Year数据来自我的控制器,其中包含ff代码:\

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;

我得到的错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

考虑用户提交表单和验证机制失败(返回相同视图)的情况,ViewBag.Year传递给null时具有DropDownListFor值(因为它没有重新填充)在POST请求之后)并抛出ArgumentNullException

要解决此问题,只需在POST方法中返回相同视图时重新填充ViewBag.Year,方法是复制如何在GET方法中填充ViewBag.Year,如下例所示:

[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);
}

类似问题:

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

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