ASP .NET - What's going on behind an Eval()?

烂漫一生 提交于 2019-12-05 00:16:33

问题


I'm trying to understand how Eval() works for a specific purpose. I'm working on a project I don't really know and I need to read some data and put them in drop down list. These data are already read and are displayed inside an ItemTemplate. I noticed there are read using the Eval() method. Something like:

<ItemTemplate>
   <a href="...=<%# Eval("foo") %>></a>
</ItemTemplate>

I need to know where Eval is getting these data from in order to discover where I should read them for my drop down list! But I didn't really understand how it works! I know that Eval() evaluates data binding expressions at runtime but where do you think I should take a look at?

Thank you


回答1:


This is a good resource: http://bytes.com/topic/asp-net/answers/447041-databinder-eval-mystification

Some reasons why to avoid it: http://weblogs.asp.net/jgalloway/archive/2005/09/20/425687.aspx

One way to improve by explicit cast: http://dotnettipoftheday.org/tips/use-explicit-casting-instead-of-databinder.eval.aspx

HTH.




回答2:


Eval is a shortcut, sort of. It is an actual method call, though, unlike Bind, which is more like a code snippet.

The MSDN article on Data-Binding Expressions should give you a really good overview.

Put simply, the parser, when it reads the page, calls DataBinder.Eval and passes in the current DataItem in context along with the string you're specifying. It's a lot like reading columns from a DataReader.

The DataItem in context depends on where this is happening. In, say, a GridView, this will probably be like a DataRow object in a DataTable that the GridView was bound to, but it can be any object really since it works via reflection. In the case of a DataRow, Eval("Foo") would try to extract data from the Foo column of the DataRow.

You can see now where this could go bad. If the DataRow stops including a Foo column, then the Eval call will fail miserably but not until runtime since there is no strong type/name checking involved.



来源:https://stackoverflow.com/questions/2630584/asp-net-whats-going-on-behind-an-eval

标签