Click here to Skip to main content
14,830,769 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Below is the error on my view page.
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'CategoryList

I had tried lots of things to solve this problem but I can't got a perfect solution about my question.

What I have tried:

model code and the model class name is admin.
public string usertype { get; set; }

Controller code(generate the option for dropdown list):
public ActionResult Addnewuser()
        List<SelectListItem> CategoryList = new List<SelectListItem>();
        CategoryList.Add(new SelectListItem { Text = "Client", Value = "Client" });
        CategoryList.Add(new SelectListItem { Text = "Consultant", Value = "Consultant" });
        ViewBag.categoryList = CategoryList;
        return View("Adminhome");

View page:
@Html.DropDownList("CategoryList", (IEnumerable<SelectListItem>)ViewBag.categoryList, "Please Select", new { @class = "form-control enquirybox", id = "drpdwncategory" })
Updated 27-Nov-20 0:29am
F-ES Sitecore 27-Nov-20 4:30am
Use a "SelectList" to pass to your DropDownList rather than just an IEnumerable of SelectListItem. The SelectList object contains properties that say which property to use for the Text and the Value of your items. Google "Html.DropDownList SelectList" for code examples.
Member 14743579 27-Nov-20 5:24am
I know about selectlist but it was not available or shown me a error on selectllist section

1 solution

The error means that ViewBag.categoryList is not set.

The fact that your view name doesn't match your action name make me suspect you have another action called AdminHome which isn't populating the ViewBag.categoryList variable.

Either that, or you are re-disaplying the same view when the form is submitted, and you've forgotten to repopulate the ViewBag variable in your POST action.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900