怎么CreateChildControls()会在Render()后面执行?(Page类)
如果是一般的aspx页面,习惯上要动态加载控件是放在CreateChildControl()里面的,在里面创建Control然后用this.Controls.Add()来添加。但是现在我是在一个HttpHandler里面使用Page就出问题了。
HttpHandler部分代码如下:
public void ProcessRequest(HttpContext context)
{
HttpApplicationState Application=HttpContext.Current.Application;
Cache Cache=HttpContext.Current.Cache;
HttpRequest Request=HttpContext.Current.Request;
HttpResponse Response=HttpContext.Current.Response;
HttpServerUtility Server=HttpContext.Current.Server;
HttpSessionState Session=HttpContext.Current.Session;
CustomPage page=new CustomControl();
StringBuilder stringBuilder=new StringBuilder();
StringWriter stringWriter=new StringWriter(stringBuilder);
HtmlTextWriter htmlTextWriter=new HtmlTextWriter(stringWriter);
page.RenderControl(htmlTextWriter);
Response.Write(stringBuilder.ToString());
}
然后中CustomPage(CustomPage继承自Page类)如同往常一样使用CreateChildControls():
protected override void CreateChildControls()
{
this.Controls.Add(new Button())
}
理论上会出现一个完全空的Button,客户端代码就象这样:
<input type="submit" name value="" />
但实际上什么都没有出现。
然而如果把HttpHandler的ProcessRequest()改动一下关键部分成如下:
public void ProcessRequest(HttpContext context)
{
HttpApplicationState Application=HttpContext.Current.Application;
Cache Cache=HttpContext.Current.Cache;
HttpRequest Request=HttpContext.Current.Request;
HttpResponse Response=HttpContext.Current.Response;
HttpServerUtility Server=HttpContext.Current.Server;
HttpSessionState Session=HttpContext.Current.Session;
CustomPage page=new CustomControl();
StringBuilder stringBuilder=new StringBuilder();
StringWriter stringWriter=new StringWriter(stringBuilder);
HtmlTextWriter htmlTextWriter=new HtmlTextWriter(stringWriter);
page.Controls.Add(new Button()); //关键在于在Render前添加Control。
page.RenderControl(htmlTextWriter);
Response.Write(stringBuilder.ToString());
}
于是页面就正常了。
现在我的问题是,怎么CreateChildControls()会跑到Render()后面啦?我不是很清楚Page的执行机制,更不清楚System.Web.UI.PageHandlerFactory是怎么运作的(我就是想模仿他的基本功能——无html部分的纯class Page)。