3

The question seems to have been asked many times, but I can't find an answer that helped me.

I have code in the code-behind of a master page file which sets a cookie when a dropdown control is changed. If I comment out the redirect line I can see that the cookie is properly set, because creating a new cookie and outputting its value successfully displays the new value of the changed dropdown.

If I allow the redirect to take place, however, the code in the page_load will report that the cookie set is null. Any help is greatly appreciated!

protected void ThemeSelection_SelectedIndexChanged(object sender, EventArgs e)
{

    HttpCookie themeCookie = new HttpCookie("PreferredTheme");
    themeCookie.Expires = DateTime.Now.AddMonths(3);
    themeCookie.Value = ThemeSelection.SelectedValue;

    Request.Cookies.Add(themeCookie);

    HttpCookie cookieCheck = Request.Cookies.Get("PreferredTheme");
    Response.Write(cookieCheck.Value);

    Response.Redirect(Request.Url.ToString());

}

protected void Page_Load(object sender, EventArgs e)
{

    HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");

    if (preferredTheme == null)
    {
        Response.Write("PreferredTheme is null");
    }

}
J S
  • 3,324
  • 4
  • 20
  • 27

1 Answers1

4

If you want the cookie to survive between requests, you need to use Response.Cookies....to send the cookie to the client. When the next Request comes in, the cookie will be there.

When to use Request.Cookies over Response.Cookies?

Community
  • 1
  • 1
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • Came here to fix my question because I realized my stupid error and saw that you had responded. Thanks! – J S Sep 02 '14 at 02:27