I encountered this error " There is no ViewData item of type IEnumerable that has the key 'StatusOptions' " when I try to use DropDownListFor and point to a select list
I know there are a lot of questions regarding this already but none of them solved my problem.
Say I'm implementing a dropdown list as filter for tasks based on the their statuses. So the FilterView correspond to FilterModel, but the controller is a more generic PageController which correspond to PageModel, so I cannot have the list of statuses contained in the model rather than ViewBag or ViewData.
I also don't want to hardcode the statuses in the view since they are backed by external service.
This is what I'm doing right now:
public class FilterModel
{
public string SelectedStatus {get;set;}
}
in my PageController:
public Result ListTasks()
{
...
ViewBag.StatusOptions = new SelectList (
new[] { "New", "Pending", "Completed"}.Select(x => new SelectListItem { Value = x, Text = x }),
"Value",
"Text"
);
...
}
in my View:
Html.DropDownListFor(model => model.SelectedStatus, (IEnumerable<SelectListItem>)ViewBag.StatusOptions)
I also tried casting it to SelectList or using ViewData['StatusOptions'], neither works.