2

我正在创建一个 MVC 项目,并且我正在使用 razor 作为我的视图。我对下拉列表的感觉有点基本的问题。我有一个下拉列表,我想从之前页面中的文本框中填充它,所以我将它放入一个对象中。我正在填充列表,但它不是完全动态的。

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

我像这样填充选择列表:

 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");
        }
    }
}

我需要这是完全动态的。这只允许四种可能性。我知道这是一件小事,我对此并不了解。所以我可能有 3 个客户,或者我可能有 7 个客户。如何在不需要计数器的情况下遍历所有客户端并添加它们?非常感谢。

4

1 回答 1

2

您可以尝试使用 Linq to Objects .Select()方法重载,在通过序列迭代时给出元素的索引:

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");
}
于 2013-11-26T15:22:58.720 回答