473,387 Members | 1,779 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

MVC, Cookies, jQuery... is my cookie being cached?

Hi,

Been trying to get to the bottom of a bug, which I thought was the browsers fault, but it turns out is either:

a) a bug in the browser.
b) a bug in jquery cookie handler.
c) a bug in MVC response handler.

Simple way to replicate this...

Controller

Expand|Select|Wrap|Line Numbers
  1. public class HomeController : Controller
  2. {
  3.     public ViewResult Index(String id)
  4.     {
  5.         var cookie = Request.Cookies["test"] ?? new HttpCookie("test") { Expires = DateTime.Now.AddDays(1) };
  6.  
  7.         cookie.Value = (!String.IsNullOrEmpty(id)) ? id : "a new cookie";
  8.  
  9.         Response.Cookies.Add(cookie);
  10.  
  11.         return View();
  12.     }
  13. }
  14.  
View

Expand|Select|Wrap|Line Numbers
  1. <div id="debug"></div>
  2.  
  3. <script type="text/javascript" src="/Scripts/jquery.cookie.js"></script>
  4. <script type="text/javascript">
  5.     var cookieString = $.cookie("test");
  6.     $("#debug").html(cookieString);
  7.     $.cookie("test", cookieString + " another bit");
  8. </script>
  9.  
(Note: Use the path /Home/Index/{id}, since using the root path (/) appears to work as it should.)

Now, when you load up the page for the first time, you'll see the text "a new cookie" (or whatever you put as the id).

If you hit refresh, the server will receive back the modified cookie (i.e. what jquery modified). BUT you should still see the same output result since the server code should reset the cookie.

But instead, it just keeps adding " another bit" on to the end continuously.

Am I missing something really obvious? Or is the cookie getting cached somewhere and ignoring the server update?

Originally I thought the problem was if you put in an {id}, and then manually changed the address to /Home/Index without an {id}, somehow the cookie update by javascript was being dropped.

I also thought that this was working fine in Firefox, and only IE had the problem, but I've since seen the same behaviour in Firefox.

Regards,
Rob.
Oct 20 '10 #1

✓ answered by peridian

Finally figured this out.

You were right, it is technically doing what I have asked it to, what is misleading is the encapsulation of the data that Microsoft has chosen to employ.

If you look at Response.Cookies when it first loads the code, it is empty.

If Request.Cookies has the cookie already set up in there, when it does Response.Cookies.Add, the Response.Cookies collection shows the added cookie on its own (as expected)

HOWEVER so does the Request.Cookies.

It appears that Response.Cookies is some kind of sub-collection of Request.Cookies. They aren't the same collection but they are interlinked.

So although Response.Cookies implies that you are responding with only the one cookie

IN FACT you are sending the contents of Request.Cookies back, which contains two cookies. The newly modified one AND the original.

From that point on the code is just adding duplicates to the collection, and all code is only ever working with one of the cookies (selected presumably by the order they appear in), so it looks like the cookie is never being changed, when in fact it is but is being stored alongside the original.

After some further testing, it appears that in order to get this right, you must set the expiry date of the incoming cookie you are updating so that it expires at the browser side, and then actively remove it from the Request.Cookies (call .Remove) before you add it to the Response.Cookies collection.

Otherwise it keeps duplicating.

Rob.

6 7367
Oralloy
988 Expert 512MB
@peridian,

The code is working as you wrote it.

Line 7 of your controller simply copies back the cookie to the view each time you refresh the page.

Basically, the (returned) cookie is sent to the view "as-is" when it's set, and set to "a new cookie", only if it doesn't exist.

So, since the view updates the cookie each pass, you see the sequence:
""
"a new cookie"
"a new cookieanother bit"
"a new cookieanother bitanother bit"
"a new cookieanother bitanother bitanother bit"
...

Am I making sense to you?
Oct 20 '10 #2
So you're saying that cookie.Value = "a new value" does not actually set the value of the cookie that is sent back??

Regardless of whether the cookie already existed or not (i.e. line 5 creates a new one or uses the existing one), line 7 should have reset the value.
Oct 21 '10 #3
Oralloy
988 Expert 512MB
I could be that I misunderstand line 5.

Aren't you saying to create a new cookie, only if Request.Cookies["test"] does not exist?

This page might help. It's a reference for the ?? operator.

Of course, now that I look at your code some more, what's the value of id supposed to be?
Oct 21 '10 #4
Note: All of this code is test code, derived from my actual code. My actual code is more complicated but this simplifies demonstration of the problem.

Value of Id could be anything, its only there for testing purposes (you can actually remove the parameter and the reference to it on line 7, and the same problem still occurs).

In MVC routing, the id parameter is optional, it was just so I could test what happens if I change the value it uses to set the cookie value, rather than constantly using "a new value".

This code should run line 5, which says grab the existing cookie if there is one, and if not, then create a new one (that is intentional, the use of the ?? was a concise way to ensure that a cookie would exist if it did not already).

Regardless of whether it used the existing one or a newly created one, line 7 should then run and set the Value property of the cookie object, regardless of whether it had already been set, modified, or not.

The next line should add the cookie back to the response and send it back to the browser.

It's as though the '.Value =' line is only applicable after it first instantiates the cookie.

When I debug the code, I can see the modified cookie coming in, and that in the runtime when it sets Value, the resulting object is setup correctly. I can also see that the Cookies collection correctly stores the object with the updated value.

But when I debug the script in the browser, it clearly see the old cookie value, not the new one.

Weird.
Oct 21 '10 #5
Finally figured this out.

You were right, it is technically doing what I have asked it to, what is misleading is the encapsulation of the data that Microsoft has chosen to employ.

If you look at Response.Cookies when it first loads the code, it is empty.

If Request.Cookies has the cookie already set up in there, when it does Response.Cookies.Add, the Response.Cookies collection shows the added cookie on its own (as expected)

HOWEVER so does the Request.Cookies.

It appears that Response.Cookies is some kind of sub-collection of Request.Cookies. They aren't the same collection but they are interlinked.

So although Response.Cookies implies that you are responding with only the one cookie

IN FACT you are sending the contents of Request.Cookies back, which contains two cookies. The newly modified one AND the original.

From that point on the code is just adding duplicates to the collection, and all code is only ever working with one of the cookies (selected presumably by the order they appear in), so it looks like the cookie is never being changed, when in fact it is but is being stored alongside the original.

After some further testing, it appears that in order to get this right, you must set the expiry date of the incoming cookie you are updating so that it expires at the browser side, and then actively remove it from the Request.Cookies (call .Remove) before you add it to the Response.Cookies collection.

Otherwise it keeps duplicating.

Rob.
Nov 2 '10 #6
Oralloy
988 Expert 512MB
Rob,

For some reason I didn't see a notification of your response last week. Sorry for dropping the conversation like that, I know how frustrating these bugs can be, and when you're finally talking with someone, and they disappear, well that's just annoying (having been there a few times myself).

Anyway, I'm glad you solved your problem with the sequencing of cookies, and the odd mixing of request and response cookies. I'd have thought those two lists would have been maintained completely independently, even though many of the cookies (session, etc) should be similar or identical between the two.

Thanks for posting your success, I've added it to my personal knowledge base.

Cheers!
Nov 2 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: chrism | last post by:
Hello, I have a pop-up window that I would like to appear in front of the browser home page when a user opens IE. Problem is, I'd like it to never appear again if the user navigates back to the...
1
by: Mike | last post by:
I got the code below from an earlier post but I can't get it to work (I get an error on the "for (i=0; i<a.length; i++)" line) Anyone have code that works for cookies with keys? > Anyone...
6
by: Denna | last post by:
Hello, I'm having a little trouble with cookies, I can write one when I press a button using the following code:- HttpCookie myCookie = new HttpCookie("MyTestCookie"); myCookie.Value =...
3
by: Wysiwyg | last post by:
After a server created cookie is processed on the client I want it removed, cleared, or expired in the javascript block but have been unable to do this. If I set a cookie value in the server code...
5
by: Miljana | last post by:
Hi, I have one problem with cookies in ASP.NET application. It seems that I can not retreive cookie from Request.Cookies collection. I put cookie in Response.Cookies collection, and after page...
3
by: Calvin KD | last post by:
Hi everyone, Can someone tell me what's wrong with the way that i read a cookie as below: private void Page_Load(object sender, System.EventArgs e) { Response.Cookies.Clear(); HttpCookie...
2
by: Alan Silver | last post by:
Hello, I have discovered that if I try and add a cookie when one by that already exists, nothing happens. No error, but the cookie is not set to the new value. For example (this is running in...
3
by: Phillip N Rounds | last post by:
I'm having trouble with using cookies to monitor the stages of login. I have a two stage Registration page ( register.aspx ) and my target page ( MyPage.aspx ) I'm using a cookie named LoginStatus...
5
by: Kevin Blount | last post by:
I've setup a method (C#) that I can call, passing it a cookie name, then a name-value pair. The idea is that as I can't append to a cookie, I read the cookie value, append by name=pair to the end...
3
by: Inny | last post by:
I want To offer a login Option, two Checkboxs, 1 labeled 'normal' the other labeled 'Forever'. I want to assign the check boxes to switch between the cookie script below (normal) and An altered...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.