在ASP.NET中,<%# Eval
和<%# Bind
是数据绑定表达式的两种常见形式,主要用于在数据绑定控件(如GridView
、Repeater
等)中显示或编辑数据。它们的核心区别在于数据绑定模式和功能:
<%# Eval
<%# Bind
TextBox
),修改后的值会自动回传到数据源。GridView
的EditItemTemplate
等使用。| 特性 | Eval
| Bind
|
|---------------------|--------------------------------|--------------------------------|
| 绑定方向 | 单向(只读) | 双向(读写) |
| 数据回传 | 不支持 | 支持(需控件启用编辑状态) |
| 性能 | 更高(无回传逻辑) | 略低(需处理更新逻辑) |
| 使用场景 | 仅显示数据 | 需编辑并提交数据 |
Eval
的典型场景:Repeater
、DataList
的只读项)。DataBinder.Eval
):DataBinder.Eval
):Bind
的典型场景:GridView
的EditItemTemplate
中编辑字段。FormView
/DetailsView
的插入或更新操作。Bind
不生效?DataBind()
方法。IEditableObject
(如DataTable
默认支持,自定义对象需手动处理)。Page_Load
中调用DataBind()
:Page_Load
中调用DataBind()
:Eval
抛出“数据为空”异常null
。Bind
在非编辑模式下报错Bind
只能在支持双向绑定的模板(如EditItemTemplate
)中使用。Eval
,编辑模板中用Bind
。<asp:GridView ID="gridView1" runat="server" AutoGenerateEditButton="true"
OnRowEditing="gridView1_RowEditing" OnRowUpdating="gridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="用户名">
<ItemTemplate>
<%# Eval("UserName") %> <!-- 只读模式 -->
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUser" runat="server" Text='<%# Bind("UserName") %>' /> <!-- 编辑模式 -->
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Eval
。Bind
。Eval
,避免不必要的双向绑定开销。没有搜到相关的文章