多個頁面向同一目標頁面PostBack的問題

1. 如果是單個頁面 A.aspx  傳遞參數 到頁面 B.aspx,可以通過設置A中的postBackUrl="~/B.aspx",或者使用 Server.Transfer("~/B.aspx")。在目標頁面 B.aspx 中,通過 PreviousPageType VirtualPath="~/A.aspx" 的強類指定源頁面 A.aspx。這樣,可以在B.aspx中通過 FindControl() 來獲得A.aspx中的控件;或者,在A.aspx中把控件定義為公共屬性,這樣,在B.aspx中可以直接按 A.property 的方式訪問

2. 當多個頁面 A1.aspx, A2.aspx,..., An.aspx 同時要傳遞參數到頁面 B.aspx 時,同樣我們可以使用 postBackUrl或者Server.Transfer()機制建立聯系。但是這個時候,由于A1,A2,...,An可能是不同類型的頁面,故無法直接使用PreviousPageType VirtualPath 的強類指定,而且,在.aspx 中關鍵字 PreviousPageType 也只能出現一次。這個時候的解決辦法是,在B.aspx中不使用關鍵字 PreviousPageType,而在B.aspx.cs中通過如下代碼來判定是哪個源頁面是PreviousPage:

if (Page.PreviousPage.AppRelativeVirtualPath == "~/A1.aspx")
{
    Label lblA1= (Label)Page.PreviousPage.FindControl("lblA1");
    ...
}
else if(Page.PreviousPage.AppRelativeVirtualPath == "~/A2.aspx")
{
    ...
}
else if ...
{
    ...
}

這里同樣使用 FindControl() 來獲得源頁面的控件引用。直接通過屬性訪問的方式應該也可以,我沒有再測試

3. 網上提到過一種方法,就是使用Interface來解決,有興趣的可以研究研究:

http://pluralsight.com/blogs/fritz/archive/2005/10/14/15566.aspx

我是試了半天,沒有成功,就放棄了。

4. 順便說一下 FindControl()

最常見也最讓人頭疼的就是 "Object reference not set to an instance of an object" 錯誤了。因為FindControl()需要從上往下逐級才能找到目標控件,特別是使用了master page的時候就更加麻煩。這個時候,需要使用如下的訪問形式:

Label lblA1= (Label)Page.PreviousPage.FindControl("ctl00$ContentPlaceHolder1$lblA1");