Why use IEnumerable?

4

I have the following code in a Controller:

       var carro = new List<SelectListItem>
        {
            new SelectListItem {Text = "Pegeout", Value = "Pegeout"},
            new SelectListItem {Text = "Chevrolet", Value = "Chevrolet"},
            new SelectListItem {Text = "Renault", Value = "Renault"},
        };
        ViewBag.Carros = carro;

And the following code in my View:

@Html.DropDownListFor(model => model.Categoria, IEnumerable<SelectListItem> ViewBag.Carros, "-Selecione-")

But I can not figure out why to use an IEnumerable to pass my SelectListItem.

    
asked by anonymous 15.05.2015 / 03:34

1 answer

3

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.

    
15.05.2015 / 04:26