开发者

How cookie creation works?

I am working on Cookies. I followed http://asp.net-tutorials.com/state/cookies/ tutorial. Here Page_Load checks for BackgroundColor cookie and if it exists it will fetch the value and set the background color else on onselectedindexchanged event a new cookie will be created.

Here after setting the cookie for first time to Red color, I try to change the drop down value again to green, so the flo开发者_高级运维w of control will reach Page_Load first and it will fetch the cookie value Red and set the background color as Red , next the control will flow to ColorSelector_IndexChanged and again a new cookie for Green will be created with the name BackgroundColor.

When I change the drop down value again Blue, irrespective of Expire time, the newly created Green Cookie should be displayed correct? Because when I change the drop down to Green, a new cookie is created and saved but still the browser is in Red color.

So how does the cookie creation works? As the cookie name is same Why didn't the Green Cookie replace Red cookie here ?


Looking at the code in the sample it doesn't look like it could ever work as if the cookie already exists it set's the value of the dropdown list to the colour held in the cookie. Then by the time the code gets to 'ColorSelector_IndexChanged' the value of the dropdown has already been altered and so the cookie is just recreated with the same colour.

Check for PostBack in page_load code and it should work as follows:

    protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Request.Cookies["BackgroundColor"] != null)
        {
            ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value;
            BodyTag.Style["background-color"] = ColorSelector.SelectedValue;
        }
    }
}

Explanation

This is because in the asp.net page life-cycle Page_Load will get called before the SelectedIndexChanged Event so you are changing the selected value of the dropdownlist before you write it to the cookie.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜