Best Way to DataBind a List with sub-related content (For example, SO's questions with tags)

后端 未结 2 504
一个人的身影
一个人的身影 2021-01-27 04:12

Using ASP.net 2.0, how do I present the information to the user similar to the Questions list on SO where each question has some child items (like the tags).

I would pro

相关标签:
2条回答
  • 2021-01-27 04:44

    If you do two separate queries, you can still make them in one call to the database, and get back two resultsets.

    Instead of DataSets, you could use the more efficient DataReader (with two resultsets). Loop through the resultsets and populate Question objects with associated Tag objects or properties. Put those objects in an ArrayList or a generic List, and you can bind it to your Repeater.

    Instead of doing anything in code-behind, you should consider moving that code to at least a data access layer (class) if you don't need a business logic layer (another class).

    All of these suggestions only apply if your app is non-trivial. Using OO methods does add to the code, but if you are doing anything beyond displaying the information, it would be better to start off with a good OO architecture (DAL and BLL, if not MVC).

    0 讨论(0)
  • 2021-01-27 05:02

    I would definitely avoid the second approach - you don't want to hit the database everytime you databind a parent item. As DOK says, try and architect your system properly. For me that would mean populating a collection of business objects and binding to it. I do something similar with a custom menu control (note this nests three datalists, but you could use repeaters):

    In the aspx page:

    <asp:DataList ID="dlMenuOne" runat="server" onitemdatabound="dlMenu_ItemDataBound" >
                <ItemTemplate>
                 //your object
    
                    <asp:DataList ID="dlMenuTwo"  runat="server" onitemdatabound="dlMenuTwo_ItemDataBound">
                    <ItemTemplate>
                    //your object's child items
    
                        <asp:DataList ID="dlMenuThree" runat="server">
                        <ItemTemplate>
                           //child item's child items    
                        </ItemTemplate>
                        </asp:DataList>
    
                    </ItemTemplate>
                    </asp:DataList> 
    
                </ItemTemplate>
                </asp:DataList>
    

    then in the code behind:

    protected void dlMenu_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        DataListItem parentList = e.Item;
        DataList dlMenuTwo = (DataList)parentList.FindControl("dlMenuTwo");
        MenuItem item = (MenuItem)parentList.DataItem;
        dlMenuTwo.DataSource = _menu.GetChildItems(item);
        dlMenuTwo.DataBind();
    }
    

    this method basically gets a reference to the object being bound (parentList.DataItem) and then binds the nested DataList to the child items (_menu.GetChildItems(item))

    0 讨论(0)
提交回复
热议问题