C# 具有未知值量的Dropdownlist

C# 具有未知值量的Dropdownlist,c#,asp.net,C#,Asp.net,我有一个下拉列表,我想将我的字典绑定到它,其中键是显示的项目,值存储在值属性标签中 我发现: 但它不允许绑定数量未知的项目,因为您必须手动输入SelectListItem。我试过这个: @Html.DropDownList("OverrideConfigList", new List<SelectListItem> { for(KeyValuePair<string, string> entry in Model.IdentifiFIConfiguration

我有一个
下拉列表
,我想将我的
字典
绑定到它,其中键是显示的项目,值存储在
属性标签中

我发现:

但它不允许绑定数量未知的项目,因为您必须手动输入
SelectListItem
。我试过这个:

@Html.DropDownList("OverrideConfigList", new List<SelectListItem>
{
     for(KeyValuePair<string, string> entry in Model.IdentifiFIConfiguration.Config.Configuration)
     {
         new SelectListItem { Text = entry.Key, Value = entry.Value}
     }
})

您的尝试很接近,但语法错误。不能在这样的列表初始值设定项中执行
for
循环

本质上,您要做的是将一个事物的集合(键/值对)转换为另一个事物的集合(
SelectListItem
s)。您可以使用LINQ select执行此操作:

Model.IdentifiFIConfiguration.Config.Configuration.Select(c => new SelectListItem { Text = c.Key, Value = c.Value })
您可能需要在末尾添加一个
.ToList()
.ToArray()
,以便进行静态键入或更快地实现集合,但这不会影响语句的逻辑

此转换将产生所需的
SelectListItem
s列表:

@Html.DropDownList(
    "OverrideConfigList",
    Model.IdentifiFIConfiguration.Config.Configuration.Select(c => new SelectListItem { Text = c.Key, Value = c.Value })
)

不能将下拉列表绑定到词典 您需要标量属性来绑定选择值 您还需要一个集合来绑定dropdownlist 你可以这样做,但那很难看

@Html.DropDownList("SelectedItemValue", new SelectList(MyDictionary, "Key", "Value"))

模型类看起来像什么?@FahadJameel用模型编辑我已经编辑了你的标题。请看,“,其中的共识是“不,他们不应该”。@JohnSaunders谢谢,我会记住的!我爱你,非常感谢你!这对我帮助很大。
@Html.DropDownList(
    "OverrideConfigList",
    Model.IdentifiFIConfiguration.Config.Configuration.Select(c => new SelectListItem { Text = c.Key, Value = c.Value })
)
@Html.DropDownList("SelectedItemValue", new SelectList(MyDictionary, "Key", "Value"))