Reputation: 3496
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");
}
}
Upvotes: 3
Views: 11201
Reputation: 20620
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?
Upvotes: 4