0

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

P.S. You don't state in your example how the code in AnimalHandler links up with your Animal class.
Sorry I misunderstood you :) +1
Is it really as simple as that?! That's ridiculous haha. The only problem I can possibly see, is the value that is passed. Is there a way to change the value given. I'm planning the URL structue to look like /Dogs/Grey-Hound for example.
0

What about something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.