将字典绑定到转发器

XSL*_*XSL 40 c# asp.net data-binding dictionary repeater

我有一个字典对象,<string, string>并希望将其绑定到转发器.但是,我不确定在aspx标记中放置什么来实际显示键值对.没有抛出错误,我可以使用它List.如何在转发器中显示字典?

Joe*_*Joe 46

一个IDictionary<TKey,TValue>也是一个ICollection<KeyValuePair<TKey, TValue>>.

你需要绑定到(未经测试)的东西:

((KeyValuePair<string,string>)Container.DataItem).Key
((KeyValuePair<string,string>)Container.DataItem).Value
Run Code Online (Sandbox Code Playgroud)

请注意,返回项的顺序是未定义的.它们可能会按照小字典的插入顺序返回,但这不能保证.如果您需要保证订单,请SortedDictionary<TKey, TValue>按键排序.

或者,如果您需要不同的排序顺序(例如按值),您可以创建一个List<KeyValuePair<string,string>>键值对,然后对其进行排序,并绑定到排序列表.

:我在标记中使用此代码来单独显示键和值:

<%# DataBinder.Eval((System.Collections.Generic.KeyValuePair<string, string>)Container.DataItem,"Key") %>
<%# DataBinder.Eval((System.Collections.Generic.KeyValuePair<string, string>)Container.DataItem,"Value") %>
Run Code Online (Sandbox Code Playgroud)


小智 32

<%# Eval("key")%> 为我工作.


Jas*_*kan 11

绑定到字典的值集合.

myRepeater.DataSource = myDictionary.Values
myRepeater.DataBind()
Run Code Online (Sandbox Code Playgroud)

  • 是.字典中的对象是KeyValuePairs,因此您可以在Joe的答案中显示DataItem. (2认同)