1.QueryString()方法
传递的值会显示在浏览器中,可以传递一个或多个值,对于安全要求不高的数据可以采用这种方法,但不支持传递数组和对象
HTML
<div>
<a href="b.aspx?id=1&&name=text">url传值</a>
</div>
b.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["id"].ToString();
string name = Request.QueryString["name"].ToString();
Response.Write(id + " " + name);
}
2.使用Application对象变量
Application对象的作用范围是整个全局,对所有用户都有效。其常用的方法用Lock和UnLock。
a.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
Application["name"] = "Test";
Response.Redirect("b.aspx");
}
b.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Application.Lock();
string name = Application["name"].ToString();
Application.UnLock();
Response.Write(name);
}
3.Session对象变量
Session存储在服务器,作用范围为单用户,过量存储会耗费大量的服务器资源,是最常用的的方法
a.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
Session["name"] = "Test";
Response.Redirect("b.aspx");
}
b.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string name = Session["name"].ToString();
Response.Write(name);
}
Cookie存于客户端,与Session一样,作用范围为单用户,配合asp.net的Request对象使用
a.aspx.cs
protected void Button_Click(object sender, EventArgs e)
{
HttpCookie cookie_name = new HttpCookie("name");
cookie_name.Value = "TestCookie";
Response.Cookies.Add(cookie_name);
Response.Redirect("b.aspx");
}
b.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string name = Request.Cookies["name"].Value.ToString();
Response.Write(name);
}
5.Server.Transfer()方法
Session需要服务器返回两次,Server.Transfer()方法需要服务器返回一次,该方法将页面引导到新页面,新页面使用前一个页面的应答流,面向对象。
a.aspx.cs
public partial class a : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string Name { get { return "TestServerTrans"; } }
protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("b.aspx");
}
}
注意:b.aspx页面中第一句加上这句代码
<%@ Reference Page="~/a.aspx"%><%--注意这里,如果有子目录,请自己添加子目录--%>
b.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
a newWebform = (a)Context.Handler;
string name = a.Name;
Response.Write(name);
}