ASP.NET中使用Server.Transfer()方法在页间传值 实例

时间:2023-03-09 17:04:01
ASP.NET中使用Server.Transfer()方法在页间传值 实例

以下代码在VS2008中测试通过

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm1.aspx.cs" Inherits="WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class WebForm1 : System.Web.UI.Page
{
public string Time
{
get { return DateTime.Now.ToString(); }
}
public string TestFun()
{
return "Function of WebForm1 Called";
} protected void Page_Load(object sender, EventArgs e)
{
Context.Items.Add("Context", "Context from Form1"); }
protected void Button1_Click(object sender, EventArgs e)
{
//this.TextBox2.Text =Request ["TextBox1"].ToString ();
Server.Transfer("WebForm2.aspx", true);//第二个参数为false时,WebForm2.aspx中不能获得TextBox1的内容 }
}

WebForm2.aspx  源码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm2.aspx.cs" Inherits="WebForm2" %>
<%@ Reference Page="~/WebForm1.aspx"%><%--注意这里--%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, 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;
}
}

摘自与:http://blog.****.net/vchao13/article/details/5004502