Bind dictionary to repeater

前端 未结 4 761
小蘑菇
小蘑菇 2020-12-29 01:53

I have a dictionary object and would like to bind it to a repeater. However, I\'m not sure what to put in the aspx markup to

4条回答
  •  抹茶落季
    2020-12-29 02:18

    Write a property in your code-behind of the type of an entry in your bound dictionary. So say, for example, I am binding a Dictionary to my Repeater. I would write (in C#) a property like this in my code-behind:

    protected KeyValuePair Item
    {
        get { return (KeyValuePair)this.GetDataItem(); }
    }
    

    Then, in my view I can use code segments like this:

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

    This makes for much cleaner markup. And while I would prefer less generic names for the values being referenced, I do know that Item.Key is a Person and Item.Value is an int and they are strongly-typed as such.

    You can (read: should), of course, rename Item to something more symbolic of an entry in your dictionary. That alone will help reduce any ambiguity in the naming in my example usage.

    There is certainly nothing to prevent you from defining an additional property, say like this:

    protected Person CurrentPerson
    {
        get { return ((KeyValuePair)this.GetDataItem()).Key; }
    }
    

    And using it in your markup thusly:

    <%# this.CurrentPerson.FirstName %>
    

    ...none of which prevents you from also accessing the corresponding dictionary entry's .Value.

提交回复
热议问题