.NET 页面间传值的几种方法


1. QueryString

  这是最简单的传值方式,但缺点是传的值会显示在浏览器的地址栏中且不能传递对象,只适用于传递简单的且安全性要求不高的数值。

  传递:  location.href="WebForm2.aspx?name=" + yourName ;

  接收:  string name = Request.QueryString["name"];

2. Form

  传递:  根据表单内控件的name和value传递,如:

       <form id="form1" method="post">

          <input type="text" name="name" value="xxx" />

       </form>

       表单需要被提交<input type="submit" /> 或者 document.getElementById("form1").submit();

  接收:  string name = Request.Form["name"];

3. Session

  需要注意的是在Session变量存储过多的数据会消耗比较多的服务器资源,在使用session时应该使用一些清理动作来去除一些不需要的session。

  移除:  Session.Remove("name");

  传递:  Session["name"] = yourName;

  接收:  string name=Session["name"].ToString();

4. Cookie

  传递:  HttpCookie cookie_name = new HttpCookie("name");

       cookie_name.Value = yourName;

       Response.AppendCookie(cookie_name);

  接收:  Request.Cookies["name"].Value;

5. Application

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

  传递: Application["name"] = name;

  接收: Application.Lock();

      string name = Application["name"].ToString(); 

      Application.UnLock();

      //Lock的目的是为了防止被多线程篡改,保证这一时刻只有自己在改

6. Server.Transfer

  传递:

  WebForm1写好需要被传值的属性  如:

  public string Name { get{ return txtName.Text; } }

  执行Server.Transfer("WebForm2.aspx");

   

  接收:

  WebForm2中接收参数:

  WebForm1 wf1=(WebForm1)Context.Handler;

  Response.Write( wf1.Name );

原文地址:https://www.cnblogs.com/dengshaojun/p/3613326.html