Ultigma
Ultigma

Reputation: 535

Looping through a list inside a HTML.DropDownList C# MVC

I have been trying to loop through a list inside of a drop down list but it doesn't seem to be working. Here's the code.

public class AnimalHandler
{
    public List<string> DogBreeds = new List<string>()
    {
       "Affenpinscher","Lhasa Apso","Shitzu", "Tibetan Terrier"
    }
}

And then in the view

Project1.Models.AnimalHandler animal = new Project1.Models.AnimalHandler();

@Html.DropDownList("breed", new List<SelectListItem> { 
    foreach(var item in animal.DogBreeds)
    {
          new SelectListItem {Text="item", Value=""},
    }
    new SelectListItem {Text="Choose a Breed", Value=""}
})

My thought behind it would be that var item would loop through all the items in the DogBreeds however there seems to be an error and I can't figure out what it could be.

Perhaps there is another SIMPLE way of doing this? Thanks

Upvotes: 0

Views: 1876

Answers (2)

Paddy
Paddy

Reputation: 33867

Something like this:

@Html.DropDownList("breed", new SelectList(animal.DogBreeds), "Choose a breed")

From comments, to set a selected value:

@Html.DropDownList("breed", new SelectList(animal.DogBreeds, 
                                             "Great Dane"), 
                                              "Choose a breed")

Where you get your selected value from is down to you.

Upvotes: 3

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15148

What about something like:

@Html.DropDownList(
    "breed", 
    animal.DogBreeds.Select(x => new SelectListItem { Text = x, Value = x }), 
    "Choose a Breed")

Upvotes: 0

Related Questions