When an object in TempDataDictionary is read, it will be marked for deletion at the end of this request.
This means that if you put something in TempData as
TempData["value"] = "someValueForNextRequest";
And on another request you will get access to it, the value will be there, but as soon as you read it, the value will be marked for deletion:
//second request, read value and is marked for deletion object value = TempData["value"]; //third request, value is not there as it was deleted at the end of the second request TempData["value"] == null
The Peek and Keep methods allow you to read a value without marking it for deletion. Say we go back to the first query where the value was stored in TempData.
With Peek you get the value without marking it for deletion with a single call, see msdn :
//second request, PEEK value so it is not deleted at the end of the request object value = TempData.Peek("value"); //third request, read value and mark it for deletion object value = TempData["value"];
With Keep you specify the key that was marked for deletion that you want to keep. Retrieving an object and then saving it when deleted are two different calls. See msdn
//second request, get value marking it from deletion object value = TempData["value"]; //later on decide to keep it TempData.Keep("value"); //third request, read value and mark it for deletion object value = TempData["value"];
You can use Peek when you always want to save a value for another query. Use Keep when storing the value depends on additional logic.
You have 2 good questions about how TempData works here and here.
Hope this helps!
Daniel JG Jan 21 '14 at 9:34 2014-01-21 09:34
source share