Reputation: 31
I attempt to save the selection of a dropdown to a cookie in the SelectedIndexChanged event.
protected void BranchNumberList_SelectedIndexchanged(object sender, EventArgs e)
{
HttpCookie myCookie = new HttpCookie("default_Loc", BranchNumberList.SelectedValue);
myCookie.Expires = DateTime.Now.AddDays(365);
Response.Cookies.Add(myCookie);
ViewDate.Enabled = true;
SelectEverything();
}
myCookie looks fine and I can see it in the response object with a quickwatch.
I try to retrieve it on the next login when this method is called from Page_Load.
private void BranchName()
{
DatabaseHelpers dh = new DatabaseHelpers();
DataSet DrpDownSrc = dh.FillBranchSelection(objConn);
BranchNumberList.DataSource = DrpDownSrc;
BranchNumberList.DataTextField = "BranchName";
BranchNumberList.DataValueField = "LocationID";
BranchNumberList.DataBind();
BranchNumberList.Items.Insert(0, "Select a branch");
try
{
BranchNumberList.SelectedValue = this.Request.Cookies["default_Loc"].Value;
}
catch (Exception)
{
BranchNumberList.SelectedIndex = 0;
}
}
I always get 'this.Request.Cookies["default_Loc"]' is null.
Can anyone see where I am going wrong?
Upvotes: 3
Views: 3989
Reputation: 2197
Your code looks OK.
The problem could either be that the server is never sending the cookie to the browser, or the browser is not handling the cookie as you would like it to.
The first thing I suggest is to determine if the cookie is being sent to the browser. Use a tool like Fiddler or Wireshark to inspect the HTTP traffic between the server and browser.
If the server is not sending the cookie, perform the following checks:
web.config
file for an httpCookies section. If it's present, check the requireSSL
setting. If requireSSL
is set to true (i.e. https), but the web site tries to send the cookie over plain http, the cookie won't be sent to the browser.Cookies.Clear
or Cookies.Remove
.If the cookie is being sent to the browser, the next step is to find out if the browser is handling the cookie properly. Try the following in at least two different kinds of browsers (e.g. Internet Explorer, Google Chrome, FireFox, etc.):
http://www.my_web_site.com/
) (see Internet Explorer Cookie Internals (FAQ)), and IE 11 has problems with cookies in IFrames and modal popups (SO discussion). IE 11 also changed its User Agent string, which causes even more problems with cookies.Upvotes: 2