ASP.NET跨页面传值技巧总结

1.使用QueryString变量

QueryString是一种非常简单的传值方式,他可以将传送的值显示在浏览器的地址栏中。如果是传递一个或多个安全性要求不高或是结构简单的数值时,可以使用这个方法。但是对于传递数组或对象的话,就不能用这个方法了。下面是一个例子:

 1 private void Button1_Click(object sender, System.EventArgs e)   
2
3 {
4
5 string s_url;
6
7 s_url = "b.aspx?name=" + Label1.Text;
8
9 Response.Redirect(s_url);
10
11 }

b.aspx.csC#代码

1 private void Page_Load(object sender, EventArgs e)   
2
3 {
4
5 Label2.Text = Request.QueryString["name"];
6
7 }

2.使用Application 对象变量

Application对象的作用范围是整个全局,也就是说对所有用户都有效。其常用的方法用LockUnLock

a.aspx.csC#代码

1 private void Button1_Click(object sender, System.EventArgs e)   
2
3 {
4
5 Application["name"] = Label1.Text;
6
7 Server.Transfer("b.aspx");
8
9 }

b.aspx.csC#代码

 1 private void Page_Load(object sender, EventArgs e)   
2
3 {
4
5 string name;
6
7 Application.Lock();
8
9 name = Application["name"].ToString();
10
11 Application.UnLock();
12
13 }

3.使用Session变量

想必这个肯定是大家使用中最常见的用法了,其操作与Application类似,作用于用户个人,所以,过量的存储会导致服务器内存资源的耗尽。

a.aspx.csC#代码

1 private void Button1_Click(object sender, System.EventArgs e)   
2
3 {
4
5 Session["name"] = Label.Text;
6
7 }

b.aspx.csC#代码

1 private void Page_Load(object sender, EventArgs e)   
2
3 {
4
5 string name;
6
7 name = Session["name"].ToString();
8
9 }

4.使用Cookie对象变量

这个也是大家常使用的方法,与Session一样,其是什对每一个用户而言的,但是有个本质的区别,即Cookie是存放在客户端的,而session是存放在服务器端的。而且Cookie的使用要配合ASP.NET内置对象Request来使用。

a.aspx.csC#代码

 1 private void Button1_Click(object sender, System.EventArgs e)   
2
3 {
4
5 HttpCookie cookie_name = new HttpCookie("name");
6
7 cookie_name.Value = Label1.Text;
8
9 Reponse.AppendCookie(cookie_name);
10
11 Server.Transfer("b.aspx");
12
13 }

b.aspx.csC#代码

1 private void Page_Load(object sender, EventArgs e)   
2
3 {
4
5 string name;
6
7 name = Request.Cookie["name"].Value.ToString();
8
9 }

5.使用Server.Transfer方法

这个才可以说是面象对象开发所使用的方法,其使用Server.Transfer方法把流程从当前页面引导到另一个页面中,新的页面使用前一个页面的应答流,所以这个方法是完全面象对象的,简洁有效。

a.aspx.csC#代码

 1 public string Name   
2
3 {
4
5 get{ return Label1.Text;}
6
7 }
8
9 private void Button1_Click(object sender, System.EventArgs e)
10
11 {
12
13 Server.Transfer("b.aspx");
14
15 }

b.aspx.csC#代码

 1 private void Page_Load(object sender, EventArgs e)   
2
3 {
4
5 a newWeb; //实例a窗体
6
7 newWeb = (source)Context.Handler;
8
9 string name;
10
11 name = newWeb.Name;
12
13 }
















posted @ 2012-04-06 10:56  烧点饭  阅读(177)  评论(0编辑  收藏  举报