There is no ViewData item of type 'IEnumerable<SelectListItem> Error

Kmcnet 706 Reputation points
2024-06-20T20:22:00.95+00:00

Hello everyone and thanks for the help in advance. I am trying to populate a select list from viewdata and a receiving the error "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'codes'".

My controller code:

            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "Sick", Value = "%992%" });
            items.Add(new SelectListItem { Text = "Well", Value = "%993%" });
            ViewBag.codes = new SelectList(items.ToList(), "Value", "Text");

and the view

@Html.DropDownList("codes", ViewBag.codes as SelectList)


I've done quite a few searches, but can't figure out what I am doing wrong. Any help would be appreciated.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,345 questions
{count} votes

4 answers

Sort by: Most helpful
  1. AgaveJoe 27,421 Reputation points
    2024-06-20T21:56:18.52+00:00

    The syntax is...

    @Html.DropDownList("codes")
    

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    4 deleted comments

    Comments have been turned off. Learn more

  3. Bruce (SqlWork.com) 60,361 Reputation points
    2024-06-21T00:34:30.3766667+00:00

    you are storing the list in ViewBag, but trying to access from ViewData. try:

    ViewData["codes"] = new List<SelectListItem>
    {
        new SelectListItem { Text = "Sick", Value = "%992%" },
        new SelectListItem { Text = "Well", Value = "%993%" }
    };
    
    0 comments No comments

  4. SurferOnWww 2,406 Reputation points
    2024-06-21T01:54:21.85+00:00

    Your code should work. Using the code copied from your question, dropdown is shown as expected:

    result

    I guess that the ViewBag is not properly given to the View. When the ViewBag is not set in the Controller like below:

    Controller

    Your error is reproduced:

    Error

    0 comments No comments