ASP. NET Eval for data binding

  • 2020-06-03 06:16:55
  • OfStack

Assuming that you already know the mechanics of ASP.NET Eval 1.1 data binding (Container in particular being a local variable), here's a look at what improvements ASP.NET Eval 2.0 data binding makes.

ASP. NET Eval 2.0's data binding function Eval() simplifies ASP. NET Eval 1.1's mysterious Container. DataItem, such as data binding expressions:


<%# (Container.DataItem as DataRowView)["ProductName"].ToString() %>

ASP.NET Eval 1.1 is simplified as :(Eval is implemented by reflection and will not be covered in this article)

<%# DataBinder.Eval(Container.DataItem, "ProductName").ToString() %>

ASP. NET Eval 2.0 is simplified as, and the local variable of Container is removed:

< %# Eval("ProductName") % >

So how does Page.Eval () know that "ProductName" is an attribute of that data, that is, is ES43en.DataItem really gone?

ASP. NET Eval() is the method of TemplateControl, the parent class of Page

TemplateControl.Eval() calculates Container automatically, which is obtained from an dataBindingContext:Stack stack.

1. Establishment of DataItem Container stack:

In ES65en.DataBind (), set up so that the child control's DataItem Container is always at the top of the stack.


public class Control
{
protected virtual void DataBind(bool raiseOnDataBinding)
{
bool foundDataItem = false; if (this.IsBindingContainer)
{
object o = DataBinder.GetDataItem(this, out foundDataItem);
if (foundDataItem)
Page.PushDataItemContext(o); <--  will DataItem Onto the stack 
}
try
{
if (raiseOnDataBinding)
OnDataBinding(EventArgs.Empty);
DataBindChildren(); <--  Bound child control 
}
finally
{
if (foundDataItem)
Page.PopDataItemContext(); <--  will DataItem Pop up the stack 
}
}
}

2. Get DataItem Container

public class Page
{
public object GetDataItem()
{
...
return this._dataBindingContext.Peek(); <--  Read from the top of the stack DataItem Container, It's binding DataItem Container
}
}

3. TemplateControl.Eval()

public class TemplateControl
{
protected string Eval (string expression, string format)
{
return DataBinder.Eval (Page.GetDataItem(), expression, format);
}
}

Conclusion:

It can be seen from the above that Page.Eval () still refers to Container.DataItem when calculating, but this DataItem is calculated automatically by DataItem Container stack. I think Page.Eval () seems to simplify the problem, but actually makes the problem more mysterious.


Related articles: