There is no ViewData item of type… issue

孤街醉人 提交于 2019-12-11 09:54:51

问题


I'm working on an intranet, precisely on an activity report system that lists the activity per week of an Employee. So I'm able to select the Employee in question with a DropDownList but I'm having issues with the selection.

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

As you can see, pl2 contains the list of Employees with the help of pr.ListEmployee(), the following DropDownList fills up :

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

But when I select an Employee it gives me the following error :

System.InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'Employee'.

I find it odd since the list does fill up with the names.


回答1:


The error occurs because the value of ViewBag.EmployeeList is null (in which case the fallback of DropDownList() is to use the first parameter as the IEnumerable<SelectListItem> property).

Since you have correctly populated it in the GET method, the error is occuring because you return the view in the POST method and have not reassigned the value of ViewBag.EmployeeList



来源:https://stackoverflow.com/questions/33098823/there-is-no-viewdata-item-of-type-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!