Frage

I'm creating an MVC project and I'm using razor for my views. I'm stuck on a slightly basic issue I feel with dropdown lists. I have a drop down list that I want to populate from text boxes in the page before, so I put it into an object. I'm populating the list, but it's not completely dynamic.

public class FormInformation
{
    public IEnumerable<SelectListItem> ListItems { get; set; }
    public string[] SelectedItems { get; set; }
    public ServiceObject serviceObject { get; set; }
}

I populate the select list like this:

 private SelectList CreateSelectListItems(int counter, List<string> clients)
    {
        if (counter == 1)
        {
            return new SelectList(new[]
                    {
                        new {id = 1, Name = ""},
                        new {id = 2, Name = clients[0]},
                    }, "Id", "Name");
        }
        if (counter == 2)
        {
            return new SelectList(new[]
                    {
                        new {id = 1, Name = ""},
                        new {id = 2, Name = clients[0]},
                        new {id = 3, Name = clients[1]},
                    }, "Id", "Name");
        }
        if (counter == 3)
        {
            return new SelectList(new[]
                    {
                        new {id = 1, Name = ""},
                        new {id = 2, Name = clients[0]},
                        new {id = 3, Name = clients[1]},
                        new {id = 4, Name = clients[2]},
                    }, "Id", "Name");
        }
        else
        {
            return new SelectList(new[]
                    {
                        new {id = 1, Name = ""},
                        new {id = 2, Name = clients[0]},
                        new {id = 3, Name = clients[1]},
                        new {id = 4, Name = clients[2]},
                        new {id = 5, Name = clients[3]},
                    }, "Id", "Name");
        }
    }
}

I need this to be completely dynamic though. This only allows for four possibilities. I know it's something small that I'm not understanding about this. So I may have 3 clients, or I may have 7 clients. How do I go about iterating through all of the clients and adding them without needing a counter? Thank you very much.

War es hilfreich?

Lösung

You could try to use Linq to Objects .Select() method overload that gives index of element while itereting through sequeance:

private SelectList CreateSelectListItems(List<string> clients)
{
    clients.Insert(0, "");
    var items = clients.Select((el, index)=> new {id = index + 1, Name = el})
                       .ToList();
    return new SelectList(items, "Id", "Name");
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top