我正在创建一个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个客户。如何在不需要计数器的情况下迭代所有客户端并添加它们?非常感谢你。
答案 0 :(得分: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");
}