Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TempData won't destroy after second request

I'm putting a value into TempData on first request in an actionfilter.

filterContext.Controller.TempData["value"] = true;

after that a second request comes in and I check for the value

filterContext.Controller.TempData.ContainsKey("value")

the value is there. Then a third request comes in and I check for the value again

filterContext.Controller.TempData.ContainsKey("value")

and the value is still present. Shouldn't be this value destroyed after the second request ? All request are AJAX requests.

like image 343
user49126 Avatar asked Oct 10 '12 09:10

user49126


People also ask

Is there any way to keep or preserve TempData value to multiple request?

You can use Keep() when prevent/hold the value depends on additional logic. when you read TempData one's and want to hold for another request then use keep method, so TempData can available for next request as above example.

Can TempData persist across action redirects?

TempData is used to pass data from current request to subsequent request (i.e., redirecting from one page to another). Its life is too short and lies only till the target view is fully loaded. But you can persist data in TempData by calling the method Keep () .

What is the different between TempData keep () and Peek ()?

temdata uses TempDataDictionary where every data read, will be marked as available for deletion, keep() and peek() both are used to retain data, the only difference is, keep() will be used to retain data that has been marked for deletion (Read and Keep), whereas peek() will be used where you want to read data without ...

What is difference between ViewData and TempData?

To summarize, ViewBag and ViewData are used to pass the data from Controller action to View and TempData is used to pass the data from action to another action or one Controller to another Controller.


1 Answers

Shouldn't be this value destroyed after the second request ?

Only if you read it:

var value = filterContext.Controller.TempData["value"];

If you don't read the value from the TempData it won't be evicted.

Here's how the TempData.Items getter is defined:

public object get_Item(string key)
{
    object obj2;
    if (this.TryGetValue(key, out obj2))
    {
        this._initialKeys.Remove(key);
        return obj2;
    }
    return null;
}

Notice how the value will be evicted only if you call the getter and only if the value was found in the collection. In the code you have shown all you do is check whether the TempData contains a given key but you haven't read the value of this key.

You could manually evict the TempData value if you want:

filterContext.Controller.TempData.Remove("value");

And there's also a method which allows you to read the value without removing it:

var value = filterContext.Controller.TempData.Peek("value");
like image 152
Darin Dimitrov Avatar answered Sep 24 '22 06:09

Darin Dimitrov