TempData will not be destroyed after the second request

I put the value in TempData on the first request in the actionfilter.

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

after this comes the second request, and I check the value

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

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

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

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

+10
asp.net-mvc asp.net-mvc-3
Oct 10
source share
1 answer

Should this value not be destroyed after the second request?

Only if you read it:

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

If you do not read the value from TempData, it will not be displayed.

Here's how getter TempData.Items :

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

Please note how the value will be displayed only if you call the getter and only if this value was found in the collection. In the code you specified, all you do is check if TempData contains the given key, but you have not read the value of this key.

You can manually display the TempData value if you want:

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

And also a method that allows you to read a value without deleting it:

 var value = filterContext.Controller.TempData.Peek("value"); 
+30
Oct 10
source share



All Articles