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

ASP.NET界面重定向传值

2017-01-08 00:33 204 查看
这么说吧,当程序启动时,ASP.NET会自动创建一些经常使用的类的实例,而这些实例就是ASP.NET的内置对象,常用的实例对象有:Response(来自HttpResponse类)、Request(来自HttpRequest类)、Server(来自HttpServerUtility类)、Application、Session、Context等,这些对象下又可以调很多方法。所谓界面重定向,就是跳转界面,发送一URL请求,有时候顺带传递点参数啥的。当完成一种要求时如果有多个解决方案,说明这个‘要求’分为好几种情况,各个方案也是各有利弊,无万全之策。下面介绍下重定向的几种常用方法。

QueryString:

最常用的传递方式,可高效传递数字或文本值,导航栏会显示参数值,所以缺乏安全性,可传递对象

Session:

导航栏不会显示参数,可传对象,大小不限,缺点是占用资源多

用例:用户第一次访问时,将定义的Session变量存储在服务器端,当再次访问时可以直接从Session对象中的集合获取相关数据,多为论坛、购物车、网站后台管理登陆系统使用,

Application:

导航栏不会显示参数,可传对象,占用资源少

Cookie:

导航栏不会显示参数,由于传递的数据大小被大多数浏览器限制为4096byte,所以用来存储用户ID之类的标识符

A界面:发送

//QueryString
protected void BtnQuery_Click(object sender, EventArgs e)
{
Response.Redirect("B.aspx?name2="+TextBox3.Text.Trim()+"&"+"name4="+TextBox4.Text.Trim());
}
//Session
protected void BtnSess_Click(object sender, EventArgs e)
{
//Session.Contents.Add("name3",TextBox3.Text);
//Session.Add("name3",TextBox3.Text);
Session["name3"] = TextBox3.Text;
Session["name4"] = TextBox4.Text;
Response.Redirect("B.aspx?");
}
//Application
protected void BtnApplic_Click(object sender, EventArgs e)
{
Application["name3"] = TextBox3.Text;
Application["name4"] = TextBox4.Text;
Response.Redirect("B.aspx?");
}
//Cookie
protected void BtnCook_Click(object sender, EventArgs e)
{
HttpCookie name1 = new HttpCookie("name3");
HttpCookie name2 = new HttpCookie("name4");
name1.Value = TextBox3.Text;
name2.Value = TextBox4.Text;
Response.AppendCookie(name1);
Response.AppendCookie(name2);
Response.Redirect("B.aspx?");
}


B界面:接收

//QueryString
protected void BtnQuGet_Click(object sender, EventArgs e)
{
TextBox3.Text = Request.QueryString["name3"];
TextBox4.Text = Request.QueryString["name4"];

}
//Session
protected void BtnSessGet_Click(object sender, EventArgs e)
{
TextBox3.Text = Session["name3"].ToString();
TextBox4.Text = Session["name4"].ToString();
}
//Application
protected void btnAppli_Click(object sender, EventArgs e)
{
TextBox3.Text = Application["name3"].ToString();
TextBox4.Text = Application["name4"].ToString();

}
//Cookie
protected void BtnCook_Click(object sender, EventArgs e)
{
TextBox3.Text = Request.Cookies["name3"].Value.ToString();
TextBox4.Text = Request.Cookies["name4"].Value.ToString();
}


当然,以上是最简单最基础的重定向Demo,实际上,仅仅是介绍Cookie,就需要很多篇幅说明,Session也是一样,相对来说简单点

情景: A登录界面验证成功

处理: A界面重定向之前加一句: Session["name1"] = username; 来传递参数

跳转到B目的界面之后,在Page_Load方法中写入判断:

protected void Page_Load(object sender, EventArgs e)
{
string user = string.Empty;
if ( Session["name1"]==null)
{
user = "";
}
else
{
user = Session["name1"].ToString();
}
if (user=="")
{
Response.Write("<script language='javascript'>alert('未登录无法查看此界面');location.href='Login.aspx'</script>");
}

Label1.Text = user;
}


这样的话即使你关闭界面,再直接访问目的页,也可以成功访问,一般Session时间默认值是20min,只要不超过这个时间就可以访问

参考书籍:ASP.NET基础教程

----------市人皆大笑,举手揶揄之
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: