0

Updating the desired functionality with Cookies as it has been implemented through sessions. In my scenario, i am adding/updating a Cookie in action method and when the partial view renders it gets the previous data of the cookie. Once the page is reloaded only then it displays the updated data.

Action Method

Response.Cookies["TColumns"].Value = string.Join(",", displayListCol); ;
Response.Cookies["TColumns"].Expires = DateTime.Now.AddDays(10);
Response.Cookies["TColumns"].Domain = null;

Partial View

<%
List<string> selectedColumns = Request.Cookies["TColumns"].Value.ToString().Split(',').ToList();
//Some code
%>

Followed these MSDN links to write and read cookies in asp.net application.

Thanks!

Community
  • 1
  • 1
Wasim Bajwa
  • 395
  • 3
  • 14

1 Answers1

0

When you set a cookie, it actually adds a response header. When the client receives the response, and parses the headers, it creates the cookie locally. On the next request, the client will set a request header with the previously set cookie. Only then is the cookie seen on the server.

In your code, you're setting the cookie and trying to read it all in the same request. The cookie has not been set yet, so you cannot read it yet. There must be a new request made by the client before the cookie will be able to be read. This is why your code works once the page is refreshed. A quick way to avoid having to manually refresh the page is to redirect after setting the cookie. Regardless of how you handle it, you need another request to read the cookie after setting it.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • After some research, it seems to me as not a secure way to save cookies in redirect. http://stackoverflow.com/questions/5366635/is-it-possible-to-set-a-cookie-during-a-redirect-in-asp-net – Wasim Bajwa Jan 27 '17 at 12:45
  • For me, i got the problem solved by updating the Request object as well... `Request.Cookies["TColumns"].Value = "Updated Value";` – Wasim Bajwa Jan 27 '17 at 12:49
  • I didn't say to set the cookie in a redirect, but rather to redirect after setting the cookie. The point is simply, no matter how you achieve it, that another request must be made by the client before the cookie you set will be in effect. A redirect is simply the easiest way to achieve that goal, as it will cause the client to make a new request. – Chris Pratt Jan 27 '17 at 14:16
  • It looks to be an extra-redirect to get the latest cookie, this will surely cause some effect on application efficiency! – Wasim Bajwa Jan 30 '17 at 07:49
  • I will definitely redirect to your suggestion wherever required in future. – Wasim Bajwa Jan 30 '17 at 07:51