首页 文章

将字典绑定到转发器

提问于
浏览
39

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

4 回答

  • 43

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

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

    ((KeyValuePair<string,string>)Container.DataItem).Key
    ((KeyValuePair<string,string>)Container.DataItem).Value
    

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

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

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

    <%# DataBinder.Eval((System.Collections.Generic.KeyValuePair<string, string>)Container.DataItem,"Key") %>
    <%# DataBinder.Eval((System.Collections.Generic.KeyValuePair<string, string>)Container.DataItem,"Value") %>
    
  • 11

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

  • 29

    绑定到字典的值集合 .

    myRepeater.DataSource = myDictionary.Values
    myRepeater.DataBind()
    
  • 1

    在绑定字典中的条目类型的代码隐藏中编写属性 . 所以说,例如,我正在将 Dictionary<Person, int> 绑定到我的Repeater . 我会在我的代码隐藏中写(在C#中)这样的属性:

    protected KeyValuePair<Person, int> Item
    {
        get { return (KeyValuePair<Person, int>)this.GetDataItem(); }
    }
    

    然后,在我看来,我可以使用这样的代码段:

    <span><%# this.Item.Key.FirstName %></span>
    <span><%# this.Item.Key.LastName %></span>
    <span><%# this.Item.Value %></span>
    

    这样可以获得更清晰的标记 . 虽然我更喜欢被引用的值的通用名称较少,但我知道 Item.KeyPersonItem.Valueint 并且它们是强类型的 .

    当然,您可以(读取:应该)将 Item 重命名为更符合字典条目的内容 . 仅这一点将有助于减少我的示例用法中命名的任何歧义 .

    肯定没有什么可以阻止你定义一个额外的属性,比如说:

    protected Person CurrentPerson
    {
        get { return ((KeyValuePair<Person, int>)this.GetDataItem()).Key; }
    }
    

    并在你的标记中使用它:

    <span><%# this.CurrentPerson.FirstName %></span>
    

    ...这些都无法阻止您访问相应的词典条目 .Value .

相关问题