When should we use Keep() and Peek() methods in TempData?

TempData stores the data in TempDataDictionary. So, whenever you read any object from the TempDataDictionary, that is marked for the deletion. And on the subsequent requests, you won't be able to access those objects.

Keep() & Peek() are two methods that allow you to prevent objects from getting deleted after they read once.

Peek() in TempData

Generally, you read a value from the TempData like below & that TempData deletes the object (both key & value) once they are read.

object name = TempData["Name"]

Now, you if read this value from Peek() method, then this object will not be marked for deletion. It means that you can prevent an object in TempData from being deleted by reading it's value using Peek() method.

Keep() in TempData

Keep() is also used to prevent an object in TempData from being deleted but in this, we explicitly call Keep() method after reading the object from TempData.

//"Name" is marked for deletion
object name = TempData["Name"];
//later on we decide to keep it

We should use Peek() when we always want to retain the value. And should use Keep() when we want to retain object's value on some condition basis.

One more difference, Peek() returns value while Keep() doesn't return anything.