locked
Dropdown list - InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key RRS feed

  • Question

  • User-973886032 posted

    hi Guys,

    I have this code that works in my previous projects asp.net core 2.0 and 2.2 , its a dropdownlist with auto postback

    However in adding them to my recent 3.0 project I get the following errors below. Here is my code and the errors, please advise

    thanks

    Ehi

    Error message

    InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key "Cat"
       <div class="col-md-3 text-center div_for_col4">
                Showing all Categories
                @Html.DropDownList("Cat", ViewBag.DepartmentID as IEnumerable<SelectListItem>, "Show all Departments", new { onchange = "form.submit();", @class = "form-control-textbox-dropdownlist" })
                 

    and controller

       ViewData["DepartmentID"] = new SelectList(_context.Set<Models.Department.Departments> (), "SubCategory_Name", "SubCategory_Name");

    Thursday, July 4, 2019 9:54 AM

All replies

  • User475983607 posted

    Change the ViewData key to "Cat".

    ViewData["Cat"] = new SelectList(_context.Set<Models.Department.Departments> (), "SubCategory_Name", "SubCategory_Name");

    However, I strongly recommend that you use tag helpers rather than HTML helpers in Core.  

    https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-2.2

    You can learn how to populate select elements at the following site.

    https://www.learnrazorpages.com/razor-pages/tag-helpers/select-tag-helper

    Thursday, July 4, 2019 11:51 AM
  • User-854763662 posted

    Hi afrika , 

    I made a test project with ASP.NET Core3.0 , but no error is thrown . Here is my worked project , you could check the difference with yours .

    The error seems to be that the key of ViewData is different with ViewBag . And the name of the dropdown ("Cat") will be used when you post back your data to the server. But you'd better make the name of the dropdown be consistent with the ViewData and ViewBag .

    Best Regards ,

    Sherry

    Friday, July 5, 2019 9:44 AM