Reputation: 3823
I have an odd issue where I try to set the cookie value in Razor view like this:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
HttpCookie e = new HttpCookie("d");
e.Value = @Url.RequestContext.RouteData.Values["id"].ToString();
e.Expires = DateTime.Now.AddMonths(999); // expires after 30 days
Response.Cookies.Add(e);
}
And then I form the URL based on this cookie value like this:
@foreach(//some collection)
{
<a href="/Items/Index/@Request.Cookies["d"].Value"></a>
}
So let's say that first route id value was:
user123
And next route id value:
user1234
When the page loads first time links look like this:
/Items/Index/user123
When 2nd time I pass the route id value as user1234 link still remains the same like:
/Items/Index/user123
Only 3rd time when I refresh the page the URL then changes to:
/Items/Index/user1234
I would like to set the cookie value to a new value each time the page loads and then form the url based on that route id value which is stored in cookie...
What am I doing wrong here?
Upvotes: 0
Views: 1092
Reputation: 7793
There is nothing odd here. Think about the flow:
The view loads the first time with id user123
.The engine executes the response and creates the cookie with this value. The cookie will go with the response but it will only be available on the next request.
On the second request with id user1234
, the cookie is now available, with the value from the last response (user123
), so you get that in your link, although you are now setting it to the next value (user1234
) in the response.
In other words, you are always one step behind because you are trying to set the cookie and read the cookie at the same time. For the cookie to be set, it has to be sent back to the browser first so it can be available on subsequent requests.
You could fix this by first checking to see if the cookie exists. If it doesn't, generate your link using the value that came in the route data and set the cookie, otherwise generate the link using the value in the cookie.
Upvotes: 1