Suppose you have understood the Data Binding Mechanism of ASP. NET Eval 1.1 (especially the local variable Container). Here we mainly analyze the improvements made by ASP. NET Eval 2.0 data binding.
The data binding function Eval () of ASP. NET Eval 2.0 simplifies the mysterious Container. DataItem of ASP. NET Eval 1.1, such as the data binding expression:
Copy codeThe Code is as follows: <% # (Container. DataItem as DataRowView) ["ProductName"]. ToString () %>
ASP. NET Eval 1.1 is simplified to: (with the type specified removed, Eval is implemented through reflection, which is not described in this article)Copy codeThe Code is as follows: <% # DataBinder. Eval (Container. DataItem, "ProductName"). ToString () %>
ASP. NET Eval 2.0 is simplified to remove the local variable Container:
<% # Eval ("ProductName") %>
So how does Page. Eval () know that "ProductName" is the attribute of the data, that is, does Container. DataItem really disappear?
ASP. NET Eval () is the method of TemplateControl, the parent class of Page.
TemplateControl. Eval () can automatically calculate the Container, which is obtained from a dataBindingContext: Stack.
1. Create a DataItem Container stack:
Create in Control. DataBind () to ensure that the DataItem iner of the sub-Control is always at the top of the stack.
Copy codeThe Code is as follows: 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); <-- press DataItem into the stack
}
Try
{
If (raiseOnDataBinding)
OnDataBinding (EventArgs. Empty );
DataBindChildren (); <-- bind a child Control
}
Finally
{
If (foundDataItem)
Page. PopDataItemContext (); <-- PopDataItemContext
}
}
}
2. Get DataItem ContainerCopy codeThe Code is as follows: public class Page
{
Public object GetDataItem ()
{
...
Return this. _ dataBindingContext. Peek (); <-- read the DataItem Container at the top of the stack, which is the DataItem Container being bound.
}
}
3. TemplateControl. Eval ()Copy codeThe Code is as follows: public class TemplateControl
{
Protected string Eval (string expression, string format)
{
Return DataBinder. Eval (Page. GetDataItem (), expression, format );
}
}
Conclusion:
Page. eval () still references Container During computation. dataItem, but this DataItem is automatically calculated through the DataItem Container stack. I think Page. eval () seems to have simplified the problem, but it actually makes the problem more mysterious.