DataBinder.Eval与Bind对比总结

一、DataBinder.Eval的基本格式

在绑定数据时经常会用到这个句程序:
<%# DataBinder.Eval(Container.DataItem,"xxxx")%>
或者
<%# DataBinder.Eval(Container,"DataItem.xxxx")%>

今天又学到一种,而且微软也说这种方法的效率要比以上两种高。
<%# ((DataRowView)Container.DataItem)["xxxx"]%>

很有用的,这样可以在前台页面做好多事情了。

还要记住要这样用必须要在前台页面导入名称空间System.Data,否则会生成错误信息。

<%@ Import namespace="System.Data" %>

这种用法其实和<%# ((DictionaryEntry)Container.DataItem).Key%>是一个道理。

Text='<%# DataBinder.Eval(Container.DataItem, "字段") %>' 这样的方法是最快的

Text='<%# GetPrice() %>' 也可以绑定方法,但方法要是public的

Text='<%# "CarDetails.aspx?CarID=" + DataBinder.Eval(Container.DataItem, "CarID") %>'

还可以连接多个字段

关键是Container这个东西,它比较神秘。它的名称空间是System.ComponentModel。对于它我还需要进一步理解。


二、DataBinder.Eval实现判断选择
<asp:TemplateColumn HeaderText="性别">
<ItemTemplate>
<%# DGFormatSex(Convert.ToString(DataBinder.Eval(Container.DataItem,"xb"))) %>
</ItemTemplate>
</asp:TemplateColumn>

cs里定义DGFormatSex方法
protected string DGFormatSex(string xb)
{
if(xb == "1")
return "男";
else
return "女";
}

DataBinder.Eval用法范例

//显示二位小数
//<%# DataBinder.Eval(Container.DataItem, "UnitPrice", "${0:F2}") %>

//{0:G}代表显示True或False
//<ItemTemplate>
// <asp:Image Width="12" Height="12" Border="0" runat="server"
// AlternateText='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "{0:G}") %>'
// ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Discontinued", "~/images/{0:G}.gif") %>' />
// </ItemTemplate>

//转换类型
((string)DataBinder.Eval(Container, "DataItem.P_SHIP_TIME_SBM8")).Substring(4,4)

{0:d} 日期只显示年月日
{0:yyyy-mm-dd} 按格式显示年月日
{0:c} 货币样式

Eval 方法是静态(只读)方法,该方法采用数据字段的值作为参数并将其作为字符串返回。Bind 方法支持读/写功能,可以检索数据绑定控件的值并将任何更改提交回数据库<%# Bind("FirstName") %>

关干这Container.DataItem就我自已的理解是有关对象转换时才要用到Container



http://blog.nnsky.com/blog_view_178492.html?page=2有DataBinder.Eval与Bind对比总结

http://www.leadbbs.com/a/a.asp?B=205&ID=712514 有DataList控件的属性的介绍

<think> 我们正在解决的是ASP.NET中数据绑定方法(如Eval(), XPath(), Bind())只能在数据绑定控件的上下文中使用的问题。根据引用内容,错误通常发生在这些数据绑定方法被用于非数据绑定控件的上下文中。以下是完整的解决方案: ### 问题原因分析 - `Eval()`和`Bind()`方法是`TemplateControl`的受保护方法,只能在实现了`INamingContainer`接口的控件内部使用(如GridView, Repeater等数据绑定控件的模板内)[^1]。 - 当在以下位置错误使用时会导致此异常: - 非模板控件属性(如普通服务器控件的属性) - 页面级代码(`.aspx`文件中的非绑定区域) - 未处于数据绑定上下文的位置 ### 解决方案 #### 1. 确保在数据绑定控件模板内使用(正确示例) ```html <!-- GridView模板列中使用Eval() --> <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateField HeaderText="产品名称"> <ItemTemplate> <!-- 正确:在ItemTemplate内部 --> <%# Eval("ProductName") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> ``` #### 2. 避免在非绑定上下文中直接使用(错误示例修正) **错误用法:** ```html <!-- 错误:在Label控件的Text属性中直接使用 --> <asp:Label Text='<%# Eval("Name") %>' runat="server" /> ``` **修正方法:** 改用数据绑定控件包裹或使用后端代码赋值 ```csharp // 后端代码(Page_Load事件中) lblName.Text = DataBinder.Eval(container.DataItem, "Name").ToString(); ``` #### 3. 复杂场景:在条件表达式中使用 引用[3]展示了在条件表达式中使用`Eval()`的方法: ```html <%# Convert.ToInt32(Eval("Status")) < 0 ? string.Format("<a href='Add.aspx?action=resubmit&id={0}'>重新提交</a>", Eval("Id")) : "" %> ``` **关键点:** - 整个表达式必须包裹在`<%# ... %>`内 - 确保位于`ItemTemplate`等模板中 #### 4. 使用DataBinder.Eval显式调用 当需要在前端非模板位置访问数据时: ```csharp // 在页面代码中(需要确保container存在) string value = DataBinder.Eval(Container.DataItem, "FieldName"); ``` **注意:** 此方法同样要求执行时存在有效的`Container`上下文 ### 特殊场景处理:在非绑定控件中显示数据 若必须在非绑定控件中使用,应采用后端绑定: 1. 在页面加载时获取数据源 2. 手动设置控件属性 ```csharp protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var data = GetData(); // 获取数据源 lblName.Text = data.Name; } } ``` ### 最佳实践总结 ```mermaid graph TD A[需要显示数据] --> B{是否在数据绑定控件模板内?} B -->|是| C[使用 <%# Eval('字段') %>] B -->|否| D[是否在服务器控件属性中?] D -->|是| E[改用后端代码赋值] D -->|否| F[检查是否在绑定上下文] ``` §§相关问题§§ 1. 如何在Repeater控件嵌套场景中正确使用Eval方法? 2. ASP.NET数据绑定控件有哪些类型及其适用场景? 3. 如何实现GridView中的双向数据绑定(Bind方法)? 4. 当数据源为XML时XPath()Eval()有何区别? 5. 如何解决数据绑定表达式中的空值处理问题? </think> ### 解决 .NET 中 Eval()、XPath() 和 Bind() 方法只能在数据绑定控件上下文中使用的问题 #### 问题原因分析 1. **上下文限制** `Eval()`, `XPath()`, `Bind()` 是 ASP.NET 数据绑定控件的 **模板方法**,只能用于以下控件的模板内: ```html <asp:Repeater>, <asp:GridView>, <asp:FormView>, <asp:ListView> ``` 2. **常见错误场景** - 在非模板区域直接使用:`<div><%# Eval("Name") %></div>` - 在普通服务器控件属性中使用:`<asp:Label Text='<%# Eval("Price") %>' />` - 在未绑定数据源的控件中使用(引用[1][2]) #### 完整解决方案 ##### 方案 1:正确放置绑定表达式(推荐) ```html <!-- GridView 模板列中使用 --> <asp:GridView ID="gvProducts" runat="server"> <Columns> <asp:TemplateField> <ItemTemplate> <!-- 正确位置 --> <%# Eval("ProductName") %> <%# XPath("Price") %> <asp:TextBox Text='<%# Bind("Quantity") %>' runat="server"/> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> ``` ##### 方案 2:处理非模板控件场景 ```html <!-- 错误示例 --> <asp:Label ID="lblPrice" Text='<%# Eval("Price") %>' runat="server"/> <!-- 修正方法:在数据绑定事件中赋值 --> protected void gvProducts_DataBound(object sender, EventArgs e) { lblPrice.Text = DataBinder.Eval(gvProducts.DataItem, "Price").ToString(); } ``` ##### 方案 3:复杂表达式处理(引用[3]) ```html <ItemTemplate> <%# Convert.ToInt32(Eval("Status")) < 0 ? string.Format("<a href='Edit.aspx?id={0}'>Edit</a>", Eval("ID")) : "N/A" %> </ItemTemplate> ``` ##### 方案 4:使用 DataBinder.Eval 扩展场景 ```csharp // 在代码后台访问数据 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { var item = GetDataItem(); // 获取数据对象 lblName.Text = DataBinder.Eval(item, "Name").ToString(); } } ``` #### 关键注意事项 1. **生命周期要求** 数据绑定表达式必须在控件的 `DataBinding` 事件触发时执行: ```mermaid graph LR A[Page_Init] --> B[控件初始化] B --> C[DataSource绑定] C --> D[DataBinding事件] D --> E[表达式执行] ``` 2. **Bind() 的特殊性** `Bind()` 仅支持 **双向绑定**,必须在支持编辑的控件中使用: ```html <asp:GridView> <EditItemTemplate> <asp:TextBox Text='<%# Bind("Email") %>' /> <!-- 正确 --> </EditItemTemplate> </asp:GridView> ``` 3. **XPath XML 数据源** 当数据源为 `XmlDataSource` 时使用: ```html <asp:Repeater DataSourceID="xmlSource"> <ItemTemplate> <%# XPath("book/title") %> <!-- 访问XML节点 --> </ItemTemplate> </asp:Repeater> ``` #### 最佳实践 1. **统一数据访问模式** ```html <!-- 安全使用示例 --> <asp:Repeater ID="repItems" runat="server"> <ItemTemplate> <div class="item"> <h3><%# Eval("Title") %></h3> <p>Price: <%# string.Format("{0:C}", Eval("Price")) %></p> </div> </ItemTemplate> </asp:Repeater> ``` 2. **错误预防检查表** - ✅ 表达式是否在以 `Template` 结尾的区域内(`ItemTemplate`, `EditTemplate`) - ✅ 父控件是否有有效的 `DataSource` - ✅ 是否在 `DataBind()` 方法调用后访问 > 经验表明,98% 的此类错误源于将数据绑定表达式放置在非模板区域(如普通 DIV 或独立控件属性中)[^1][^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值