绑定列表<dictionary <string,string>&gt; to DropDownList </dictionary <string,string>

时间:2012-03-12 07:32:06

标签: c# asp.net

var dict = new Dictionary<string,string>();
dict.Add("A","123");
dict.Add("B","456");
dict.Add("C","789");
dict.Add("D","000");
var list = new List<Dictionary<string,string>>(); //pretty much like a DataTable
list.Add(dict); //more than one dict in the list

//ddl is a dropdownlist
ddl.DataSource = list
ddl.DataTextField ="[A]";
ddl.DataValueField ="[C]";
ddl.DataBind();

对于WPF,我可以在上面进行类似的绑定,但不能在asp.net中进行。

2 个答案:

答案 0 :(得分:6)

你应该绑定你的字典,而不是列表。像这样:

var dict = new Dictionary<string,string>();
dict.Add("A","123");
...

ddl.DataSource = dict
ddl.DataTextField ="Key";
ddl.DataValueField ="Value";
ddl.DataBind();

答案 1 :(得分:3)

这对我很有用:

Dictionary<string, string> myDict = Dictionary<string, string>();
myDict.Add("myKey","My test value");

@Html.DropDownList("SomeDropDown", new SelectList(myDict, "key", "Value"),
                   "--- Select tomething ---", new { @class = "myHtmlClassName" })