How to Avoid the Eval Method for better DataBinding

Since ASP.NET 2.0, the Eval method replaced DataBinder.Eval and the syntax has become cleaner. But Eval, which is now available as a method on TemplateControl, is not really any better in terms of performance. Internally, Eval calls DataBinder.Eval and Page.GetDataItem() instead of Container.DataItem to get exactly the same result as before. There are two major issues with it: use of reflection (similar to Late Bound objects in Visual Basic), and the sytax still remains long and unpleasant, specially in complex binding situations.

If we had a strongly typed DataItem property to work with, we could avoid Eval or Reflection once for all. So instead of doing <%#Eval("FirstName")%> we would do <%#DataItem.FirstName%> and Visual Studio intellisense will make it even easier.

It is actually possible to achieve this by casting Container.DataItem to the actual type, like: <%#=(Container.DataItem as MyNameSpace.Customer).FirstName%>

But if you have to do a lot those, it is not much fun. 

Here is a better solution:

Add a protected Property on the Page with the Type of your DataItem, like this:

protected mynamespace.Customer DataItem{get{return Page.GetDataItem() as mynamespace.Customer;}}

Now, your data binding expressions can use the strongly typed DataItem and all its Properties. Better yet, you can also work with its Public Fields and Methods, something the Eval or DataBinding.Eval can not do. So now the Data Binding expression would look like:

<%#DataItem.FirstName%>

Thanks to the Page.GetDataItem() method, it is possible to get a reference to the current DataItem of the Data Binding Context from anywhere in the Page.

If you have multiple DataControls binding to collections of different Types, one strongly typed DataItem property won't  work in both DataBound Controls. In that case, simply create two properties with names like "CurrentCustomer", "CurrentProduct" etc. and use them in the right context.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag




Live preview

November 20. 2008 01:51