ASP 2.0 数据绑定函数Eval()的机制_Asp.Net开发技巧
时间:2010-09-16 来源:缘分星空
Author: Walkdan (walkdan(at)gmail.com)
ASP.NET 2.0 的Eval()简化了掉了ASP 1.1 Container.DataItem,比如:
<%# (Container.DataItem as DataRowView)["ProductName"].ToString() %>
简化为:(去掉了类型指定 ASP 1.1, Eval通过反射实现,本文不再阐述)
<%# DataBinder.Eval(Container.DataItem, "ProductName").ToString() %>
又简化为(ASP 2.0):
<%# Eval("ProductName") %>
Eval()是TemplateControl:Page 的方法
TemplateControl.Eval()可以自动计算出Container, 机制就是从一个dataBindingContext:Stack堆栈来获取。
1. 建立DataItem Container 栈:
在Control.DataBind()中,建立,这样可以保证子控件的DataItem Container始终在栈顶。
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); <-- 将DataItem压入堆栈
}
try
{
if (raiseOnDataBinding)
OnDataBinding(EventArgs.Empty);
DataBindChildren(); <-- 绑定子控件
}
finally
{
if (foundDataItem)
Page.PopDataItemContext(); <-- 将DataItem弹出堆栈
}
}
}
2. 获取DataItem Container
public class Page
{
public object GetDataItem()
{
...
return this._dataBindingContext.Peek(); <-- 读取堆栈顶部的DataItem Container,就是正在绑定的DataItem Container
}
}
3. TemplateContro.Eval()
public class TemplateControl
{
protected string Eval (string expression, string format)
{
return DataBinder.Eval (Page.GetDataItem(), expression, format);
}
}
stencil art canvas70s show musical episodemichael kors handbags on salehilarious text jokesGucci-114914Camerica cruise shipspcworldcruise land excursionsva beach apartment rentalsvegan leather jacketghurka leather goods dealerscruise line dealsall inclusive vacations cheapChanel-cc1730pick up lines kidsmens celtic ringsmonogramed gift ideascheap plastic bagsredneck jokeindependence of the seas cruise reviewstamarind beach hotel uroapersonalized mens necklacesChanel--20130--silvergolf towel manufacturersdisney cruises tipstext message jokeshow to tie a bowline knothudsons leather shop discount codeoil painting effectsprada bags 2008cheap chloe bagmarch bulletin board ideasleisure lightweight luggagemirage fighterluggage sets with garment bagthat 70 show castfendi magic bag smallzeb atlas cruiseseabourn cruises reviewmonogrammed hostess giftsbest spring break 2009make fleece hatbeaches real estatedisney vacations cruisehigh school graduation giftspromotional umbrellasshort story bookdiscount designer authenticfmag digital luggage scaledye faux leather