您的位置:首页 > 编程语言 > ASP

Asp.net页面传值的五种常用方法

2009-02-27 18:37 453 查看
最近一段时间,业余的学习主要是总结一些基本知识点,今天主要总结了一下,页面传值的几种基本方法,当然是在网上前辈们的基础上编写的,在经过自己调试。第一次写博客,就把它弄上来了。写的不对的地方,请指正。

先建立两个页面:a.aspx,b.aspx,a页面放两个TextBox,一个Button,b页面,放一个label,一个TextBox。

第一种:使用QueryString,当然我们有时候也叫url传值,传递的参数通过url实现,安全性不是很高。

a.aspx.cs

protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("b.aspx?name=" +  this.TextBox1.Text + "&id=" + this.TextBox2.Text);
}


b.aspx.cs

private void TheFirst()
{
this.TextBox1.Text = Request.QueryString["name"];
this.Label1.Text = Request.QueryString["id"];
}


第二种:使用Application对象,作用范围对每个用户都有效

a.aspx.cs

protected void Button2_Click(object sender, EventArgs e)
{
Application["name"] = this.TextBox1.Text;
Application["id"] = this.TextBox2.Text;
Server.Transfer("b.aspx");
}


b.aspx.cs

private void TheSecond()
{
Application.Lock();
this.TextBox1.Text = Application["name"].ToString();
this.Label1.Text = Application["id"].ToString();
Application.UnLock();
}


第三种:使用Cookie对象变量,这个使用的也比较多,针对客户端的,而我们用的比较多的Session是针对服务器端。

a.aspx.cs

protected void Button3_Click(object sender, EventArgs e)
{
HttpCookie cookie_name = new HttpCookie("test");
cookie_name.Values["name"] = this.TextBox1.Text;
cookie_name.Values["id"] = this.TextBox2.Text;
Response.AppendCookie(cookie_name);
Server.Transfer("b.aspx");
}


b.aspx.cs

private void TheThird()
{
HttpCookie cookie_name = Request.Cookies["test"];
this.TextBox1.Text = cookie_name.Values["name"];
this.Label1.Text = cookie_name.Values["id"].ToString();
}


第四种:使用Server.Transfer方法,其使用Server.Transfer方法把流程从当前页面引导到另一个页面中,新的页面使用前一个页面的应答流,所以这个方法是完全面象对象的,简洁有效。同时这个方法我也测试了多次,开始都调试不好,后来在csdn朋友的帮助下完成的。

这里需要说明的是,在vs05中,html代码中要加这么一句,要不就不来米。

b.aspx

<%@ PreviousPageType VirtualPath="~/Test/a.aspx"%>


a.aspx.cs

protected void Button4_Click(object sender, EventArgs e)
{
Server.Transfer("b.aspx");
}

public string MyName
{
get
{
return this.TextBox1.Text;
}
}

public string MyId
{
get
{
return this.TextBox2.Text;
}
}


b.aspx.cs

private void TheFour()
{
Test_a a; //这里注意是带文件夹的类
a = (Test_a)Context.Handler;
this.Label1.Text = a.MyName;
this.TextBox1.Text = a.MyId;
}


第五种:当然就是我们用的最多的Session,其操作与Application类似,作用于用户个人,所以,过量的存储会导致服务器内存资源的耗尽。

a.aspx.cs

private void Button5_Click(object sender, System.EventArgs e)
{
Session["name"] = Label.Text;
}


b.aspx.cs

private void TheFive()
{
this.TextBox1.Text = Session["name"].ToString();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: