首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

新手.net操作cookies

2012-02-25 
新手求助:.net操作cookies思路是这样的:做了三个按钮,点了以后加载不同的CSS文件,并通过cookies来保存用户

新手求助:.net操作cookies
思路是这样的:做了三个按钮,点了以后加载不同的CSS文件,并通过cookies来保存用户所选择的CSS信息。现在只是暂时用一个Label控件来显示用户选择了哪个CSS。

问题是:每次页面加载时Label控件上显示的字都不是cookies里所保存的。刷新页面以后得到的才是cookies里的信息。
请问一下程序是哪里错了吗?


public   partial   class   _Default   :   System.Web.UI.Page  
{
        protected   void   Page_Load(object   sender,   EventArgs   e)
        {
                if   (Request.Browser.Cookies   ==   true)
                {
                        if   (Request.Cookies[ "myStyle "]   ==   null)
                        {
                                HttpCookie   MyCookie   =   new   HttpCookie( "myStyle ");
                                MyCookie.Value   =   "style1 ";
                                Response.Cookies.Add(MyCookie);
                                this.txtName.Text   =   "you   haven   never   beet   to   this   website. ";
                        }
                        else
                        {
                                this.txtName.Text   =   Request.Cookies[ "myStyle "].Value;
                        }
                }  
        }
        protected   void   Button1_Click(object   sender,   EventArgs   e)
        {
                HttpCookie   MyCookie   =   new   HttpCookie( "myStyle ");
                MyCookie.Value   =   "style1 ";
                Response.Cookies.Add(MyCookie);
        }
        protected   void   Button2_Click(object   sender,   EventArgs   e)
        {
                HttpCookie   MyCookie   =   new   HttpCookie( "myStyle ");
                MyCookie.Value   =   "style2 ";
                Response.Cookies.Add(MyCookie);
        }
        protected   void   Button3_Click(object   sender,   EventArgs   e)
        {
                HttpCookie   MyCookie   =   new   HttpCookie( "myStyle ");


                MyCookie.Value   =   "style3 ";
                Response.Cookies.Add(MyCookie);
        }
}


[解决办法]
page_load执行在button_click之前
所以你在page_load里取到的Request.Cookies[ "myStyle "].Value是上一次button_click里设置的值
在每个button_click函数的最后加一句Response.Redirect(Request.Url.ToString());可以达到你想要的效果
.....
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie MyCookie = new HttpCookie( "myStyle ");
MyCookie.Value = "style1 ";
Response.Cookies.Add(MyCookie);
Response.Redirect(Request.Url.ToString());
}
protected void Button2_Click(object sender, EventArgs e)
{
HttpCookie MyCookie = new HttpCookie( "myStyle ");
MyCookie.Value = "style2 ";
Response.Cookies.Add(MyCookie);
Response.Redirect(Request.Url.ToString());
}
protected void Button3_Click(object sender, EventArgs e)
{
HttpCookie MyCookie = new HttpCookie( "myStyle ");
MyCookie.Value = "style3 ";
Response.Cookies.Add(MyCookie);
Response.Redirect(Request.Url.ToString());
}

热点排行