IEnumerable<SelectListItem>
is the type expected by the second parameter of all overloads of the DropDownListFor
extension method, however the ViewBag is a dynamic object - at compile time it has no way to determine which type will be the Carros
property %. So it is necessary to do the conversion (cast):
(IEnumerable<SelectListItem>)ViewBag.Dados
In this way the interpreter knows which method it should call.
The fact that the parameter is of type IEnumerable<SelectListItem>
allows you to use polymorphism and pass several different types of collection as SelectListItem[]
, List<SelectListItem>
, Collection<SelectListItem>
, etc. You could, instead of using a List < >, use an array:
SelectListItem[] items = new SelectListItem[]
{
new SelectListItem {Text = "Pegeout", Value = "Pegeout"},
new SelectListItem {Text = "Chevrolet", Value = "Chevrolet"},
new SelectListItem {Text = "Renault", Value = "Renault"},
};
And in the view, you can leave as is (convert to IEnumerable
) or change to:
@Html.DropDownListFor(model => model.Categoria, (SelectListItem[])ViewBag.Carros, "-Selecione-")
In short, you do not need to use IEnumerable
, you need to use a type that implements IEnumerable
and needs to convert the ViewBag property to the appropriate type.