没有类型...问题的ViewData项

时间:2015-10-13 09:21:17

标签: c# asp.net-mvc forms-authentication

我正在内联网上工作,正是在一个列出每周员工活动的活动报告系统上。所以我可以用DropDownList选择有问题的员工,但我对选择有疑问。

   public ActionResult Client() // ReportIndex
    {
        [...]           
        string strEmployee = "-1";
        string strUser = User.Identity.Name;

        if (null != (string)Session["ReportEmployee"])
            strEmployee = (string)Session["ReportEmployee"];

        [...]

        ProjectResourceManagerService pr = new ProjectResourceManagerService(new ModelStateWrapper(this.ModelState));
        //nea60
        IEnumerable<SelectListItem> pl = pr.ListProject(strUser, strYear, strMonth);
        IEnumerable<SelectListItem> pl2 = pr.ListEmployee();
        foreach (SelectListItem item in pl)
            if (item.Value == strProject)
                item.Selected = true;
        ViewBag.ProjectList = pl;
        foreach (SelectListItem item in pl2)
            if (item.Value == strEmployee)
                item.Selected = true;
        ViewBag.EmployeeList = pl2;

        //nea11
        Session["ReportYear"] = strYear;
        Session["ReportMonth"] = strMonth;
        //nea58
        Session["ReportProject"] = strProject;


        //nea58           

        return View();
    }

如您所见,pl2包含pr.ListEmployee()帮助下的员工列表,以下DropDownList填写:

<td>&nbsp;&nbsp;&nbsp;<%:Html.DropDownList("Employee", (List<SelectListItem>)ViewBag.EmployeeList, "", new { onchange = "this.form.submit();" })%></td>

但是当我选择Employee时,它会给我以下错误:

  

System.InvalidOperationException:没有“IEnumerable”类型的ViewData项具有“Employee”键。

我发现它很奇怪,因为列表 填充了名称。

1 个答案:

答案 0 :(得分:1)

发生错误是因为ViewBag.EmployeeList的值为null(在这种情况下,DropDownList()的回退是使用第一个参数作为IEnumerable<SelectListItem>属性。)< / p>

由于您已在GET方法中正确填充它,因此错误发生,因为您在POST方法中返回视图并且未重新分配ViewBag.EmployeeList的值

相关问题