萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

ASP.NET Repeater 巢狀繫結完整實作 (分類+產品兩層)

架構說明

  • 外層 `rptCategoryList`:繫結分類資料表
  • 內層 `rptProductList`:在 `ItemDataBound` 事件中依分類 ID 篩選產品並繫結
  • 資料來源:`DataTable` (示範用),實務可換為 Entity Framework / Dapper 查詢結果

後端程式碼 (C#)

using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class NestedRepeaterDemo : System.Web.UI.Page
{
    private DataTable dtCategory;
    private DataTable dtProduct;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            dtCategory = GetCategoryTable();
            dtProduct  = GetProductTable();

            rptCategoryList.DataSource = dtCategory;
            rptCategoryList.DataBind();
        }
    }

    // 模擬分類資料
    private DataTable GetCategoryTable()
    {
        var dt = new DataTable();
        dt.Columns.Add("CategoryId", typeof(int));
        dt.Columns.Add("CategoryTitle", typeof(string));

        for (int i = 1; i <= 3; i++)
        {
            var row = dt.NewRow();
            row["CategoryId"] = i;
            row["CategoryTitle"] = "分類 " + i;
            dt.Rows.Add(row);
        }
        return dt;
    }

    // 模擬產品資料
    private DataTable GetProductTable()
    {
        var dt = new DataTable();
        dt.Columns.Add("ProductTitle", typeof(string));
        dt.Columns.Add("CategoryId", typeof(int));

        for (int i = 1; i <= 9; i++)
        {
            var row = dt.NewRow();
            row["ProductTitle"] = "產品 " + i;
            row["CategoryId"] = i > 6 ? 3 : (i > 3 ? 2 : 1); // 1-3→分類1, 4-6→分類2, 7-9→分類3
            dt.Rows.Add(row);
        }
        return dt;
    }

    // 依分類 ID 篩選產品
    private DataTable GetProductsByCategory(int categoryId)
    {
        var dv = dtProduct.DefaultView;
        dv.RowFilter = $"CategoryId = {categoryId}";
        return dv.ToTable();
    }

    // 外層 Repeater ItemDataBound
    protected void rptCategoryList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            var drv = (DataRowView)e.Item.DataItem;

            // 顯示分類標題
            var ltlTitle = (Literal)e.Item.FindControl("ltlTitle");
            ltlTitle.Text = drv["CategoryTitle"].ToString();

            // 找到內層 Repeater 並繫結該分類產品
            var rptProductList = (Repeater)e.Item.FindControl("rptProductList");
            rptProductList.DataSource = GetProductsByCategory(Convert.ToInt32(drv["CategoryId"]));
            rptProductList.DataBind();
        }
    }

    // 內層 Repeater ItemDataBound
    protected void rptProductList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            var drv = (DataRowView)e.Item.DataItem;
            var ltlTitle = (Literal)e.Item.FindControl("ltlTitle");
            ltlTitle.Text = drv["ProductTitle"].ToString();
        }
    }
}

前端標記 (ASPX)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="NestedRepeaterDemo.aspx.cs" Inherits="Demo.NestedRepeaterDemo" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>巢狀 Repeater 示範</title>
    <style>
        .category-box {border:1px solid #ddd; margin-bottom:15px; padding:10px; border-radius:6px; background:#fafafa;}
        .category-title {font-weight:bold; font-size:1.1em; color:#333; margin-bottom:8px; padding-bottom:5px; border-bottom:1px solid #eee;}
        .product-list {list-style:none; padding:0; margin:0;}
        .product-list li {padding:5px 0 5px 20px; background:url('/images/bullet.png') no-repeat 5px center; color:#555;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="container">
            <h2>產品分類目錄</h2>
            <asp:Repeater ID="rptCategoryList" runat="server" OnItemDataBound="rptCategoryList_ItemDataBound">
                <ItemTemplate>
                    <div class="category-box">
                        <div class="category-title">
                            <asp:Literal ID="ltlTitle" runat="server" />
                        </div>
                        <ul class="product-list">
                            <asp:Repeater ID="rptProductList" runat="server" OnItemDataBound="rptProductList_ItemDataBound">
                                <ItemTemplate>
                                    <li><asp:Literal ID="ltlTitle" runat="server" /></li>
                                </ItemTemplate>
                            </asp:Repeater>
                        </ul>
                    </div>
                </ItemTemplate>
            </asp:Repeater>
        </div>
    </form>
</body>
</html>

效能優化建議

問題 解決方案
N+1 查詢:每個分類觸發一次資料庫查詢 一次撈回所有產品至 `DataTable`/`List`,記憶體中 `DataView.RowFilter` / LINQ 篩選 (如本範例)
大量資料 ViewState 膨脹 關閉 Repeater `EnableViewState="false"`,或改用 `ListView`/`GridView` 配合分頁
巢狀層級過深 (>2) 考慮扁平化資料結構、使用遞迴使用者控制項、或前端 JS 渲染 (Web API + Vue/React)

進階:使用強型別模型與 ListView

// Model
public class Category { public int Id {get;set;} public string Title {get;set;} public List<Product> Products {get;set;} }
public class Product { public string Title {get;set;} }

// 後端
var categories = repo.GetCategoriesWithProducts(); // 單一查詢含導覽屬性
rptCategoryList.DataSource = categories;
rptCategoryList.DataBind();

// 前端 (ListView 更語意化)
<asp:ListView ID="lvCategories" runat="server">
  <LayoutTemplate><div id="container"><asp:PlaceHolder ID="itemPlaceholder" runat="server" /></div></LayoutTemplate>
  <ItemTemplate>
    <h3><%#: Item.Title %></h3>
    <asp:ListView ID="lvProducts" runat="server" DataSource='<%# Item.Products %>'>
      <ItemTemplate><div><%#: Item.Title %></div></ItemTemplate>
    </asp:ListView>
  </ItemTemplate>
</asp:ListView>

結語

巢狀 Repeater 透過 `ItemDataBound` 事件動態繫結子資料源,是 WebForms 時代常見模式。現代開發建議改用 **強型別模型 + ListView/Repeater** 或 **前後端分離 (Web API + 前端框架)**,獲得更佳維護性與效能。

copyright © 萬盛學電腦網 all rights reserved