The IEnumerable<SelectListItem>
is the type expected by the second parameter of all overloads of the extension method DropDownListFor
, but Viewbag is a dynamic object - at compile time there is no way to determine which type the property will be Carros
. So it is necessary to do the conversion (cast):
(IEnumerable<SelectListItem>)ViewBag.Dados
That way the interpreter knows which method he should call.
The parameter being of type IEnumerable<SelectListItem>
allows you to use polymorphism and pass several different collection types 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 it as it is (converting to IEnumerable
) or change to:
@Html.DropDownListFor(model => model.Categoria, (SelectListItem[])ViewBag.Carros, "-Selecione-")
In short: you don’t need to use the IEnumerable
, need to use a type that implements the IEnumerable
and need to make the conversion of the Viewbag property to the appropriate type.
Thank you Marcus, your answer cleared all my questions !
– Paulo Henrique Junior