ASP.NET学习之页面传值(7)_Cookie传值
【关键点: 1、创建一个Cookie对象 2、在对象中封装要传输的数据【可以创建一个cookie对象,往里面添加多个键值对,也可以创建多个Cookie,每一个Cookie中存放一个键值对】 3、设置cookies过期的时间 4、将Cookies对象添加到Response.cookies中 5、页面跳转 【注意:在接收数据时,一定要做判空判断】 】 IndexPage.aspx页面 <form runat="server"> <div> <input id="Text1" type="text" runat="server"/> <input id="Text2" type="text" runat="server"/> <input id="Button1" value="传值" type="button" runat="server" onserverclick="ok_ServerClick"/> </div> </form> IndexPage.aspx.cs后台代码: public void ok_ServerClick(object sender, EventArgs e) { //给变量赋值 string name = Text1.Value; string pass = Text2.Value; #region 单值传递 ////创建一个Cookie对象 //HttpCookie Namecookie = new HttpCookie("Name", name); //HttpCookie Passcookie = new HttpCookie("Pass", pass); ////将Cookie对象添加到Cookies集合中 //Response.Cookies.Add(Namecookie); //Response.Cookies.Add(Passcookie); #endregion #region 多值传递 //多值传递 HttpCookie cookies = new HttpCookie("Login"); //要传输的数据的封装【方法一】 //cookies.Values.Add("Name", name); //cookies.Values.Add("Pass", pass); //要传输的数据的封装【方法二】 cookies.Values["Name"] = name; cookies.Values["Pass"] = pass; cookies.Expires = DateTime.MaxValue; //设置Cookie的过期的时间 Response.Cookies.Add(cookies); //将Cookie集合存放到Cookies中【必须要有,不然接收时,Cookies取不到值】 #endregion //页面跳转 Response.Redirect("ResultIndex.aspx"); } ResultPage.aspx.cs后台代码: protected void Page_Load(object sender, EventArgs e) { #region Cookie单值接收 //HttpCookie NameCookie = Request.Cookies["Name"]; //string name = NameCookie.Value; //HttpCookie PassCookie = Request.Cookies["Pass"]; //string pass = PassCookie.Value; #endregion if (Request.Cookies["Login"]!=null) { //获得数据方法一: HttpCookie cookie = Request.Cookies["Login"]; string name = cookie["Name"]; string pass = cookie["Pass"]; //获得数据方法二: //string name = cookie.Value; //获得Name=key1&Pass=key2 //string name = Request.Cookies["Login"]["Name"]; //string pass = Request.Cookies["Login"]["Pass"]; txt.Value = "用户名:" + name + "-----密码:" + pass; } } 多值Cookie的写法: http://www.cnblogs.com/abllyboy/archive/2010/11/29/1891395.html http://blog.csdn.net/dingzhenyang/article/details/5704582