您确实需要为每个值设置一个“键”或索引,因为您必须将每个名称转换为IEnumerable<SelectListItem>,这需要一个 ID 值和一个文本字符串才能显示。您可以使用以下两种方法之一:
使用字典
创建Dictionary<int, string>:
Dictionary<int, string> domainDict = new Dictionary<int, string>();
每次添加域时,都会添加一个数字:
domainDict.Add(1, "DomainA");
如果您有包含多个域的此信息的源列表,您可以在该列表上执行 foreach 并使用类似于我在下面显示的索引器变量,而不是手动添加项目。
你需要一个模型。创建一个名为 DomainViewModel.cs 的类并将其添加到里面:
public class DomainViewModel()
{
public int Id { get; set; }
public string Name { get; set; }
}
然后遍历您的字典以将项目添加到DomainViewModel,然后将这些项目中的每一个添加到List<DomainViewModel>,类似于我在下一节中的内容,除了它看起来像这样:
List<DomainViewModel> lstDomainModel = new List<DomainViewModel>();
foreach(KeyValuePair<int, string> kvp in domainDict)
{
DomainViewModel d = new DomainViewModel();
d.Id = kvp.Key; // number
d.Name = kvp.Value; // domain name
lstDomainModel.Add(d);
}
(跳至完成,如下)
使用循环索引器进行列表迭代
如果您不想使用Dictionary<>,您可以通过迭代List<string> 并将其直接放入List<DomainViewModel> 来即时添加索引。以下是你的做法:
1) 确保您已从上面创建了 DomainViewModel.cs 类。
2) 编辑您的控制器函数以构建您的 List<string>,然后对其进行迭代以使用索引器变量 (idx) 将其以 DomainViewModel 的块添加到新的 List<DomainViewModel>:
List<string> domains = new List<string>();
domains.Add("DomainA"); // etc.
List<DomainViewModel> lstDomainModel = new List<lstDomainModel>();
int idx = 0;
// Add your List<string> to your List<DomainViewModel>
foreach (string s in domainList)
{
DomainViewModel domainModel = new DomainViewModel();
domainModel.Id = idx;
domainModel.Name = s;
lstDomainModel.Add(domainModel);
idx++;
}
完成
使用任何一种方法,一旦你将它放在List<DomainViewModel> 中,你就可以这样做:
IEnumerable<SimpleListItem> domainList =
lstDomainModel.Select(d => new SelectListItem {
Text = d.Name,
Value = d.Id.ToString()
}
);
ViewBag.Domains = domainList;
并像这样在您的视图中显示它:
@Html.DropDownList("Domains", (IEnumerable<SelectListItem>)ViewBag.Domains)