首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 資料繫結語法完整解析:<%= %> 與 <%# %> 差異、Eval、DataBinder.Eval、ItemDataBound 實戰

     編輯:ASP.NET 基礎

兩大繫結語法比較

語法名稱執行時機適用範圍資料來源
<%= ... %>單向繫結 / 內嵌程式碼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 無法存取。

<%# %> 三種寫法

  1. Eval("欄位名"):最簡潔,自動尋找 Container.DataItem。
  2. DataBinder.Eval(Container.DataItem, "欄位名"):明確指定容器,效能略優於 Eval(避免反射尋找)。
  3. (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>

ItemDataBound 進階控制

當需要依資料內容動態調整 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 事件...
}

效能與最佳實踐建議

  • 避免過度使用 Eval:大量資料時反射開銷大,改用強型別轉型或 DataBinder.Eval。
  • 繫結時機:只在 !IsPostBack 呼叫 DataBind(),或配合 ViewState 管理。
  • 分離關注點:複雜邏輯移至 ViewModel/Presenter,模板僅負責呈現。
  • 現代替代:ASP.NET Core Razor Pages / Blazor 提供更強型別、編譯期檢查的語法(@model.Property、@foreach)。

常見錯誤排查

  1. <%# %> 放在非模板區塊 → 編譯錯誤「資料繫結運算式只能用於具有 DataBinding 事件的控制項」。
  2. Eval("NotExist") → 執行期拋例外,建議用 Eval("Field", "預設值") 多載。
  3. Container.DataItem 為 null → 確認 DataBind() 已呼叫且資料來源非空。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved