2013年2月11日 星期一

在 MasterPage 中使用 PreviousPage.FindControl

假設 source.aspx 包含兩個控制項,例如:
<asp:TextBox ID="myBox" runat="server" />
<asp:Button ID="btn" runat="server" Text="click me" onclick="btn_Click" />
in source.aspx.cs:
protected void btn_Click(object sender, EventArgs e) {
    Server.Transfer("target.aspx");
}

目標頁面 target.aspx :

<asp:Label ID="myLabel" runat="server" Text="default_text" />

接著想在 target.aspx 中使用 PreviousPage.FindControl 取得 source.aspx 的 TextBox 值,則要加入:

<%@ PreviousPageType VirtualPath="~/source.aspx" %>

then in target.aspx.cs:

if(Page.PreviousPage != null){
    var textbox = (TextBox) Page.Previous.FindControl("myBox");
    Label1.Text = textbox.Text;
}

如此則按下 source.aspx 的 Button 後,會在 target.aspx 中的 Label 顯示 Input 欄位的值。
但如果頁面是 MasterPage 裡的 ContentPage,則失效 (取到 null )。


解法:

透過 ContentPlaceHolderID,先找到 Content,再取控制項。

上面的 target.aspx.cs 改為:
if(Page.PreviousPage != null){
   var preContent =  (ContentPlaceHolder)
                   Page.PreviousPage.Master.FindControl("myContentPlaceHolderID");
    TextBox textbox = (TextBox) preContent.FindControl("myBox");
    Label1.Text = textbox.Text;
}

參考: http://www.aspnet101.com/2008/01/using-previouspage-with-a-master-page/










沒有留言:

張貼留言