<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits="WebApp.Demo" %>
<html><body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text='<%# GetName((sender as Label).ID.Substring(5)) %>' /><br />
<asp:Label ID="Label2" runat="server" Text='<%# GetName((sender as Label).ID.Substring(5)) %>' /><br />
<asp:Label ID="Label3" runat="server" Text='<%# GetName((sender as Label).ID.Substring(5)) %>' /><br />
<asp:Label ID="Label4" runat="server" Text='<%# GetName((sender as Label).ID.Substring(5)) %>' /><br />
</form>
</body></html>
關鍵點:
Text 屬性使用 **資料繫結運算式** `<%# ... %>` (非 `<%= ... %>`)。sender 繫結上下文為控制項本身 (Label),透過 ID.Substring(5) 擷取數字尾碼 (1~4) 作為索引鍵。DataBind() 觸發運算式求值。using System;
using System.Collections.Generic;
using System.Web.UI;
namespace WebApp
{
public partial class Demo : Page
{
// 資料來源:Dictionary
readonly Dictionary _nameDict = new Dictionary
{
{1, "小果"}, {2, "小磊"}, {3, "小組"}, {4, "小節"}
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
// 供行內運算式呼叫
public string GetName(object index)
{
// C# 7.0+ 模式比對 / 空值合併
int key = 0;
int.TryParse(index?.ToString(), out key);
return _nameDict.TryGetValue(key, out var name) ? name : "未知";
}
void BindData()
{
// 觸發所有 <%# %> 運算式求值
this.DataBind(); // 或 Page.DataBind()
}
}
}
Page_Load → BindData() → this.DataBind()。| 問題 | 原因 | 修正 |
|---|---|---|
| Label 顯示空白 | 未呼叫 DataBind() | 在 Page_Load 中呼叫 this.DataBind() |
| ID 非 Label1~4 格式 | `Substring(5)` 邏輯失效 | 改用 int.Parse(ID.Replace("Label","")) 或 `CommandArgument` 傳遞索引 |
| PostBack 後資料消失 | 未在 `!IsPostBack` 重新繫結 | 確保 `BindData()` 在 `!IsPostBack` 區塊 |
| 資料來源變更未反映 | ViewState 保留舊值 | 重新呼叫 `DataBind()` 或關閉 ViewState |
@* Razor 頁面 *@
@page
@model DemoModel
@foreach (var kv in Model.NameDict)
{
<label>@kv.Value</label><br>
}
// PageModel
public class DemoModel : PageModel
{
public Dictionary NameDict { get; } = new()
{ {1,"小果"},{2,"小磊"},{3,"小組"},{4,"小節"} };
public void OnGet() { }
}
優點:型別安全、智慧感應、無 ViewState、易測試、跨平台。
ASP.NET WebForms `<%# %>` 行內資料繫結運算式搭配 `DataBind()`,可將伺服端邏輯直接嵌入標記。範例展示以 Label ID 尾碼作為字典鍵值查詢的技巧。實務上建議改用 `Repeater`/`ListView`/`GridView` 等資料繫結控制項,分離資料與呈現,或直接遷移至 Razor Pages / Blazor 現代架構。