InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Department'


Question: This error has been nagging me for the past hour or so, what could be the problem. I checked for possible causes and don't seem to find the cause. See the error below:

"InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Department'"


Login to See the Rest of the Answer

Answer:
The answer is simple, if you are not simply populating your ViewBag with the List<SelectListItem> values then this error is thrown. In order to diagnose this error put a breakpoint on the View that you are expecting the SelectListItem data to be passed. Inspect the ViewBag to see if the data is actually passed into the View from the Controller. 

There is a chance that the ViewBag is empty, this is common when you are retrieving the SelectListItem from the database using an Async Function, and you happen not to await the function or the call to retrieve the SelectListItem values from the database.

If you are using the async function to get the values from the database, make sure that you await the call before returning the request to the View.

Possible causes:
1. You have cast the ViewData or ViewBag.Departments as SelectListItem or something else. This will throw an InvalidOperationException Error because the DropDownList should expect an IEnumerable of SelectListItem and not one single SelectListItem.
2. Somewhere in your code you have an Invalid casting, keep in mind to leave casting alone. The MVC DropDownList Html Tag is smart enough to know the type of incoming data.

A similar article talking about merely the same thing can be found here.
Leave a comment below if this helped you solve the problem.







For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email Address[email protected]