简体   繁体   中英

Asp.net Couldn't get the updated Cookies

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM