内置对象Cookies传值遇到汉字的时候乱码方式的解决措施

例:Default1.aspx中放置两个控件,TextBox1和Button1。Default2.aspx中放置一个控件Label1。

     功能是:当点击Button1的时候把TextBox1中的值取到Label1中去。

     用的方式是Cookies传值。

     问题:当TextBox1中放入汉字的时候,传到Label1中的将会是乱码。

     解决措施:对TextBox1中的字符进行编译,赋值到Label1中的时候再进行解码即可。

Default1.aspx中的代码如下:

 1 public partial class Default1 : System.Web.UI.Page
 2 {
 3     protected void Page_Load(object sender, EventArgs e)
 4     {
 5         Button1.Click += Button1_Click;
 6     }
 7 
 8     void Button1_Click(object sender, EventArgs e)
 9     {
10         string a = HttpUtility.UrlEncode(TextBox1.Text, System.Text.Encoding.GetEncoding("utf-8"));
11         Response.Cookies["user"].Value = a;
12         Response.Redirect("Default2.aspx");
13     }
14 }

Default2.aspx中的代码如下:

 1 public partial class Default2 : System.Web.UI.Page
 2 {
 3     protected void Page_Load(object sender, EventArgs e)
 4     {
 5         if (Request.Cookies["user"] != null)
 6         {
 7             string a = HttpUtility.UrlDecode(Request.Cookies["user"].Value, System.Text.Encoding.GetEncoding("utf-8"));
 8             Label1.Text = a;
 9         }
10     }
11 }

 

posted @ 2016-10-18 15:38  Angel落痕  阅读(510)  评论(0编辑  收藏  举报