Data saved to TempData is stored in the session and will be automatically removed at the end of the first request where the data is accessed. If never read, it will be kept until finally read or the session times out.
The typicaly usage looks like the following sequence (where each line is invoked from a different request):
//first request, save value to TempData
TempData["value"] = "someValueForNextRequest";
//second request, read value, which 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
This behavior can be further controller with the Peek
and Keep
methods.
With Peek
you can retrieve data stored in TempData without marking it for deletion, so data will still be available on a future request
//first request, save value to TempData
TempData["value"] = "someValueForNextRequest";
//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 can specify that a key that was marked for deletion should actually be retained. In this case retrieving the data and saving it from deletion requires 2 method calls:
//first request, save value to TempData
TempData["value"] = "someValueForNextRequest";
//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"];
With this in mind, use Peek
when you always want to retain the value for another request and use Keep
when retaining the value depends on additional logic.