2015-06-12 29 views
0

我有一个dropdownlist,我想将我的Dictionary绑定到它,其中键是显示的项目,值存储在value属性标记中。未知数量值的下拉列表

我发现这一点: bind-html-dropdownlist-with-static-items

但它不允许未知数量的项目被绑定,你必须手动输入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} 
    } 
}) 

但是那也没用。有什么建议么?

编辑: 我的模型类基本上是这样的:

public class DefaultConfigurationModel 
{ 
    public IdentifiFIConfiguration IdentifiFIConfiguration { get; set; } 

    public String FiKeySelection { get; set; } 

    public List<String> FiConfigKeys 
    { 
     get 
     { 
      if (IdentifiFIConfiguration.Config == null) 
      { 
       return null; 
      } 

      List<string> fiConfigKeys = new List<string>(); 

      foreach (KeyValuePair<string, string> entry in IdentifiFIConfiguration.Config.Configuration) 
      { 
       fiConfigKeys.Add(entry.Key); 
      } 

      return fiConfigKeys; 
     } 
    } 
} 

IdentifiFIConfiguration持有Config看起来像这样:

public class IdentifiConfiguration 
{ 
    public Dictionary<String, String> Configuration { get; set; } 

    public static IdentifiConfiguration DeserializeMapFromXML(string xml) 
    { 
     Dictionary<string, string> config = new Dictionary<string, string>(); 
     XmlDocument configDoc = new XmlDocument(); 
     configDoc.LoadXml(xml); 

     foreach (XmlNode node in configDoc.SelectNodes("/xml/*")) 
     { 
      config[node.Name] = node.InnerText; 
     } 

     IdentifiConfiguration identifiConfiguration = new IdentifiConfiguration() 
     { 
      Configuration = config 
     }; 

     return identifiConfiguration; 
    } 
} 
+0

模型类是什么样子? –

+0

@FahadJameel编辑模特 –

+0

我编辑了您的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

回答

2

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

本质上,你试图做的是转换一个东西(键/值对)的集合到另一个东西的集合(SelectListItem s)。你可以这样做与LINQ选择:

Model.IdentifiFIConfiguration.Config.Configuration.Select(c => new SelectListItem { Text = c.Key, Value = c.Value }) 

您可以选择需要在结尾处加上无论是静态类型或兑现收集越早.ToList().ToArray(),但不会影响到逻辑声明。

这种转变将导致要SelectListItem是清单:

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

我爱你,非常感谢你!这帮了我很多。 –

0

你不能一个下拉列表绑定到dictionnary 你需要标量属性绑定选择值 还需要一个集合绑定下拉列表 你可以做到这一点,但那个丑陋

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