显然,步骤跟上一种方法非常相似,只是使用Request.Cookies代替了Request.QueryString。
注:一些浏览器是不支持Cookies的。
3. Session 变量
接下来我们看看在服务端维持的Session变量。 Session在用户向服务端发出首次请求时被创建,而在用户关闭浏览器或异常发生时终止(其实还有过期的情况)。下面的代码是用Session来传值的例子。 我们可以看到 Session 为用户创建了“Name” 键,并把TextBox的值赋给它。
// Session 创建
Session["Name"] = txtName.Text;
Response.Redirect("WebForm5.aspx");
// 下面的代码显示如何从Session中取值
// 代码放在其它页面中
if(Session["Name"] != null)
Label3.Text = Session["Name"].ToString();
4. Application 变量
有些时候,我们需要一个值能够在所有的页面中访问,这时候我们可以使用Application变量。 如下列代码所示,一旦我们创建了Application变量并赋值,就可以在网站(项目)的所有页面中获得它。
// 为Application变量赋值
Application["Name"] = txtName.Text;
Response.Redirect("WebForm5.aspx");
// 从Application变量中取出值
if( Application["Name"] != null )
Label3.Text = Application["Name"].ToString();
5. Server.Transfer方式(或称HttpContext方式)
我们还可以使用 Server.Transfer方式(或称HttpContext方式)在页面之间传递变量,此时,要传递的变量可以通过属性或方法来获得,使用属性将会比较容易一些。好,让我们在第一个页面中来写一个用来获得TextBox值的属性:
public string GetName
{
get { return txtName.Text; }
}
我们需要使用Server.Transfer把这个值发送到另外一个页面中去,请注意Server.Transfer只是发送控件到一个新的页面去,而并不会使浏览器重定向到另一个页面。所以,我们我们在地址栏中仍然看到的是原来页面的URL。如下代码所示:
Server.Transfer("WebForm5.aspx");
接下来,我们到"WebForm5.aspx"看看:
// You can declare this Globally or in any event you like
WebForm4 w;
// Gets the Page.Context which is Associated with this page
w = (WebForm4)Context.Handler;
// Assign the Label control with the property "GetName" which returns string
Label3.Text = w.GetName;
结束语:
如我们看到的那样,各种传值方式都各有优劣,在不同的情况下选择适当的方式是很重要的。








