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

來源:互聯網
上載者:User

折騰了一段時間,對這個問題做個簡單總結:

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");

在前面的文章講popUp window的時候,也提高過類似的問題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.