了解 ASP.NET Eval() 和 Bind()
任何人都可以向我展示一些绝对最小的 ASP.NET 代码来理解 Eval()
和 Bind()
吗?
最好为我提供两个单独的代码片段或者网络链接。
Can anyone show me some absolutely minimal ASP.NET code to understand Eval()
and Bind()
?
It is best if you provide me with two separate code-snippets or may be web-links.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于只读控件,它们是相同的。对于 2 路数据绑定,使用要通过声明性数据绑定进行更新、插入等操作的数据源,您需要使用
Bind
。例如,想象一下带有
ItemTemplate
和EditItemTemplate
的 GridView。如果您在ItemTemplate
中使用Bind
或Eval
,则不会有任何区别。如果您在EditItemTemplate
中使用Eval
,该值将无法传递给DataSource
的Update
方法code> 网格绑定到的。更新:我想出了这个例子:
这是用作对象数据源的自定义类的定义:
For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use
Bind
.Imagine for example a GridView with a
ItemTemplate
andEditItemTemplate
. If you useBind
orEval
in theItemTemplate
, there will be no difference. If you useEval
in theEditItemTemplate
, the value will not be able to be passed to theUpdate
method of theDataSource
that the grid is bound to.UPDATE: I've come up with this example:
And here's the definition of a custom class that serves as object data source:
Darin Dimitrov 完美地回答了这个问题,但从 ASP.NET 4.5 开始,现在有更好的方法来设置这些绑定来替换*
Eval()
和Bind()
,利用强类型绑定。*注意:仅当您不使用
SqlDataSource
或匿名对象
时,此方法才有效。它需要一个强类型对象(来自EF模型或任何其他类)。此代码段显示了如何将
Eval
和Bind
用于ListView
控件(InsertItem
需要Bind
,正如 Darin Dimitrov 上面所解释的,ItemTemplate
是只读的(因此它们是标签),所以只需要一个Eval
):来自 ASP.NET 4.5+ 中,数据绑定控件已通过新属性
ItemType
进行了扩展,该属性指向您分配给其数据源的对象类型。Picture
是强类型对象(来自 EF 模型)。然后我们替换:所以这个:
会变成这样:
与 Eval 和 Eval 相比的优点绑定:
Source:来自 这本优秀的书
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace*
Eval()
andBind()
, taking advantage of the strongly-typed bindings.*Note: this will only work if you're not using a
SqlDataSource
or ananonymous object
. It requires a Strongly-typed object (from an EF model or any other class).This code snippet shows how
Eval
andBind
would be used for aListView
control (InsertItem
needsBind
, as explained by Darin Dimitrov above, andItemTemplate
is read-only (hence they're labels), so just needs anEval
):From ASP.NET 4.5+, data-bound controls have been extended with a new property
ItemType
, which points to the type of object you're assigning to its data source.Picture
is the strongly type object (from EF model). We then replace:So this:
Would become this:
Advantages over Eval & Bind:
Source: from this excellent book