Why use the Ienumerable?

Asked

Viewed 275 times

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’t understand why to use a Ienumerable to pass my Selectlistitem.

1 answer

3


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.

  • 1

    Thank you Marcus, your answer cleared all my questions !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.