| 語法 | 名稱 | 執行時機 | 適用範圍 | 資料來源 |
|---|---|---|---|---|
<%= ... %> | 單向繫結 / 內嵌程式碼 | Render 階段 | 頁面任意位置 | 頁面屬性、方法、欄位、控制項屬性 |
<%# ... %> | 資料繫結運算式 | DataBind() 時 | 僅限繫結控制項模板內 | Container.DataItem、Eval、DataBinder.Eval |
<%= %> 使用範例<%= Property %><br />
<%= Method() %><br />
<%= (Property + " " + Method()) %>
<asp:Label ID="Label1" runat="server"><%= TextBox1.Text %></asp:Label>
後端對應:
public string Property { get { return "This is a Property"; } }
protected string Method() { return "This is a Method"; }
注意:成員必須為 public 或 protected,private 無法存取。
<%# %> 三種寫法Eval("欄位名"):最簡潔,自動尋找 Container.DataItem。DataBinder.Eval(Container.DataItem, "欄位名"):明確指定容器,效能略優於 Eval(避免反射尋找)。(Container.DataItem as 實體類別).屬性:強型別,IntelliSense 支援、編譯期檢查、效能最好。<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="RptAllOnItemDataBound">
<ItemTemplate>
FirstName: <%# Eval("FirstName") %><br />
SecondName: <%# DataBinder.Eval(Container.DataItem, "SecondName") %><br />
FullName: <%# (Container.DataItem as DataBindEx.Person).FullName %><br />
<asp:Literal ID="Others" runat="server" />
</ItemTemplate>
</asp:Repeater>
當需要依資料內容動態調整 UI(如條件式顯示、計算衍生欄位),使用 OnItemDataBound:
protected void RptAllOnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Person pe = (Person)e.Item.DataItem;
Literal lit = e.Item.FindControl("Others") as Literal;
if (pe != null)
{
switch (pe.FirstName)
{
case "劉": lit.Text = "劉喜歡打球"; break;
case "林": lit.Text = "林喜歡下棋"; break;
default: lit.Text = "陳喜歡 C#"; break;
}
}
}
}
// 實體類別
public class Person {
public string FirstName { get; set; }
public string SecondName { get; set; }
public string FullName => FirstName + SecondName;
}
// 頁面後端
public partial class _Default : Page {
public string Property { get { return "This is a Property"; } }
protected string Method() { return "This is a Method"; }
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
var list = new List<Person> {
new Person { FirstName = "劉", SecondName = "明豐" },
new Person { FirstName = "林", SecondName = "旺" },
new Person { FirstName = "陳", SecondName = "仁峰" }
};
Repeater1.DataSource = list;
Repeater1.DataBind();
}
}
// ItemDataBound 事件...
}
DataBinder.Eval。!IsPostBack 呼叫 DataBind(),或配合 ViewState 管理。@model.Property、@foreach)。<%# %> 放在非模板區塊 → 編譯錯誤「資料繫結運算式只能用於具有 DataBinding 事件的控制項」。Eval("NotExist") → 執行期拋例外,建議用 Eval("Field", "預設值") 多載。Container.DataItem 為 null → 確認 DataBind() 已呼叫且資料來源非空。