對於每一個.NET程序員,對於ASP.NET頁面生命周期都有一定的了解和把握。關於一些細節方面請參考 http://blog.sina.com.cn/s/blog_5f7aa2970100d5h4.html,內容比較詳盡,本文將不再概述。本文主要是從 繼承以及視圖狀態,事件,委托,容器控件以及子控件這些方面來把握和控制整體的頁面生命周期。
先看下下面4個相關頁面的代碼(為降低復雜度,很多代碼被刪減與精簡,僅提供最基本的操作代碼)。僅僅 幾個文件,先看下整體文件的布局,有一個整體的把握。

(一)父類的相關事件以及處理
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1 public class UserParentPage:System.Web.UI.Page
{
/// <summary>
/// 對回傳數據的處理,以及其他內容的設置、獲取
/// </summary>
/// <param name="e"></param>
protected override void OnInit(EventArgs e)
{
Core.Trace.TraceInfo("UserParentPage OnInit");
base.OnInit(e);
//編寫相應的代碼防止SQL注入
//System.Web.HttpContext.Current.Request.QueryString/Form
//根據上下文對象來檢測,以及做出相應的處理
//以及其他一些內容的設置、控制等等
}
protected override void OnLoad(EventArgs e)
{
Core.Trace.TraceInfo("UserParentPage OnLoad");
base.OnLoad(e);
//編寫相應的代碼對整體頁面的控制
}
}
(二)用戶控件(子控件)的相關內容
Code highlighting produced by Actipro
CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1 public partial class UserEventControl : System.Web.UI.UserControl
{
public delegate void ChangedHandler();
public event ChangedHandler Changed;
private void Page_Load(object sender, System.EventArgs e)
{
Core.Trace.TraceInfo("UserEventControl OnLoad");
if (!Page.IsPostBack)
{
Core.Trace.TraceInfo("UserEventControl OnLoad !Page.IsPostBack==true");
SetContent();
}
}
private void SetContent()
{
int len =12,num = 2,perRowMaxCount=8;
System.Text.StringBuilder table = new System.Text.StringBuilder();
for (int i = 0; i <= num; i++)
{
table.Append(@"<table bordercolor='black' width='100%'><tr align='left'>");
for (int j = 0; j < perRowMaxCount; j++)
{
int p = i * perRowMaxCount + j;
if (p < len)
{
string paramValue ="param"+p.ToString();
string showValue ="show"+p.ToString();
table.Append(string.Format(@"<td width='12.5%'><a
href='javascript:__doPostBack(""{2}"",""{0}"")' CommandName=""{0}""
class='line'><font>{1}</font></a></td>", paramValue,showValue,
lbtnShow.ClientID.Replace("_lbtnShow", "$lbtnShow")));
}
else
{
table.Append(string.Format(@"<td width='12.5%'></td>"));
}
}
table.Append(@"</tr></table>");
}
lblShow.Text = table.ToString();
}
public string CurrentID
{
set
{
ViewState["CurrentID"] = value;
}
get
{
return (string)ViewState["CurrentID"];
}
}
protected override void OnInit(EventArgs e)
{
Core.Trace.TraceInfo("UserEventControl OnInit");
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.lbtnShow.Click += new System.EventHandler(this.lbtnShow_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
/// <summary>
/// 單擊時將觸發
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void lbtnShow_Click(object sender, System.EventArgs e)
{
Core.Trace.TraceInfo("UserEventControl lbtnShow_Click");
CurrentID = Request.Form["__EVENTARGUMENT"];//獲取回傳值
SetContent();//設置內容----因為有些內容被修改過,如樣式什麼的,本例忽略
Changed();//觸發事件
}
}