Thursday, April 21, 2011

There is no ViewData item with the key 'taskTypes' of type IEnumerable<SelectListItem>

I'm getting the error message above when adding an onchange attribute to a Html.DropDownList in ASP.NET MVC:

<td><%= Html.DropDownList("taskTypes", (IEnumerable<SelectListItem>)ViewData["TaskTypes"], "None", new { onchange = "document.getElementById('NewTask').submit()" })%></td>

When the view initially loads, I do not get the error. Only when posting back after the selected item is changed. My controller code is:

[AcceptVerbs(HttpVerbs.Get), RequiresAuthentication]
    public ActionResult NewTask()
    {
        List<SelectListItem> dropDownData = new List<SelectListItem>();
        List<SelectListItem> statusDropDownData = new List<SelectListItem>();

        foreach (TaskStatus t in tasks.GetTaskStatus())
        {
            statusDropDownData.Add(new SelectListItem { Text = t.Status, Value = t.TaskStatusID.ToString() });
        }

        foreach (TaskType t in tasks.GetTaskTypes())
        {
            dropDownData.Add(new SelectListItem { Text = t.Reference, Value = t.TaskTypeID.ToString() });
        }

        ViewData["TaskStatus"] = statusDropDownData;
        ViewData["TaskTypes"] = dropDownData;

        if (Request["taskTypes"] != null)
        {
            string tt = Request["taskTypes"];
        }


        return View();
    }

Does anyone know what the problem might be?

Thanks

From stackoverflow
  • The AcceptVerbs attribute on that controller method indicates that it will build up that ViewData instance and return the associated View to display your form. Are you certain that the controller method responsible for handling the form submission (or saving the data) is building up that ViewData instance in the same manner?

    Paul : Thanks, there was a typo in the Post method.

0 comments:

Post a Comment