| 方式 | 適用場景 | 範例 |
|---|---|---|
| DataSourceID | 宣告式資料源 | `DataSourceID="odsProducts"` + ` |
| DataSource + DataBind() | 程式碼動態指定 | `rpt.DataSource = GetList(); rpt.DataBind();` |
| Model Binding (4.5+) | 強型別、可測試 | `SelectMethod="GetProducts"` + `ItemType="Models.Product"` |
<%#: Item.Name %>
<%#: Item.Price.ToString("C") %>
// .aspx.cs
public IQueryable GetProducts()
{
return _db.Products.Where(p => p.IsActive).OrderByDescending(p => p.Id);
}
protected void rptProducts_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// 1. 僅處理資料列
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
return;
var product = (Product)e.Item.DataItem; // 強型別取得資料
// 2. 找控制項
var lblPrice = (Label)e.Item.FindControl("lblPrice");
var btnAdd = (Button)e.Item.FindControl("btnAdd");
var divCard = (HtmlGenericControl)e.Item.FindControl("divCard");
// 3. 依業務邏輯調整
if (product.IsOnSale)
{
lblPrice.CssClass = "price-sale";
lblPrice.Text = $"{product.Price:C} (原價 {product.OriginalPrice:C})";
}
if (product.Stock == 0)
{
btnAdd.Enabled = false;
btnAdd.Text = "缺貨中";
divCard.Attributes["class"] += " out-of-stock";
}
// 4. 交替列額外處理 (AlternatingItem 已套用 CSS,這裡可做邏輯區分)
if (e.Item.ItemType == ListItemType.AlternatingItem)
{
// 例如:偶數行顯示不同圖示
}
}
protected void rptProducts_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
int productId = Convert.ToInt32(e.CommandArgument);
// 業務邏輯:加入購物車
CartService.AddItem(productId);
// 回饋
ScriptManager.RegisterStartupScript(this, GetType(), "toast", "showToast('已加入購物車');", true);
}
else if (e.CommandName == "ViewDetail")
{
Response.Redirect($"ProductDetail.aspx?id={e.CommandArgument}");
}
}
<%#: Item.Name %>
<%#: Item.Name %>
// 後端方法簽名需符合 SelectArguments
public IQueryable GetProductsByCategory(int categoryId)
{
return _db.Products.Where(p => p.CategoryId == categoryId);
}
Repeater 是 Web Forms 時代最純粹的資料繫結控制項,掌握其模板系統、事件模型與 Model Binding,能快速產出高品質、可維護的動態 HTML。新架構請擁抱現代渲染模式。