Server.Transfer()方法在頁間傳值

來源:互聯網
上載者:User
ASP.NET Server.Transfer()是在兩個頁面之間進行傳值的好方法,從A頁面Transfer到B頁面時,就可以在B頁面通過Context.Handler獲得A頁面的一個類的執行個體,從而在B調用A的各個成員對象。

下面的樣本建立了WebForm1和WebForm2,通過Server.Transfer()方法示範在WebForm2中讀取WebForm1的文字框、讀取屬性、通過Context傳值、調用WebForm1的方法等:

WebForm1上放置一個TextBox1和一個Button1,程式如下:

public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.Button Button1;

private void Page_Load(object sender, System.EventArgs e)
{
Context.Items.Add("Context","Context from Form1");
}
public string Time
{
get{return DateTime.Now.ToString();}
}
public string TestFun()
{
return "Function of WebForm1 Called";
}
#region Web Form設計器產生的程式碼
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void Button1_Click(object sender, System.EventArgs e)
{
Server.Transfer("WebForm2.aspx", true);
}

在WebForm2上放置一個Literal1控制項,程式如下:

public class WebForm2 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Literal Literal1;

private void Page_Load(object sender, System.EventArgs e)
{
string strTxt="";
WebForm1 oForm=(WebForm1)this.Context.Handler;
strTxt+="Value of Textbox:"+Request.Form["TextBox1"] +"<br>";
strTxt+="Time Property:"+oForm.Time +"<br>";
strTxt+="Context String:"+Context.Items["Context"].ToString() +"<br>";
strTxt+=oForm.TestFun() +"<br>";
Literal1.Text =strTxt;
}

#region Web Form設計器產生的程式碼
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}

補充說明,就是Transfer方法的第二個參數指示是否保留頁面的Form和QuerryString的值,你可以試著把它設為False,則在WebForm2中將讀不到TextBox1的值。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.