Using TempData, Peek And Keep In ASP.NET MVC

In my previous article we learned ViewData, ViewBag, TempData, and Session. In this article we will learn  the uses of Peek and Keep with TempData in ASP.NET MVC application.
 
We will continue from the previous article; let us Set TempData["TempModel"] = "This is TempData Example";  in HomeController.
 
 

Set Break Point for TempData and now just run the application and check the value. 
 
 

For first call after one request we didn't fetch value in our view so TempData["TempModel"] keeps the value; see the following screen's watch window, it keeps the value which we set in Controller.
 
 
 
Now, read the TempData Value from View, and try to check the Value, 
 
 
 

It will become null because you have read the data.
 


Now, create one more TempData["TempModelKeep"], here we will first read the data, and for the next request we want to keep the data, so set the Value using TempData. Keep the method as in the following screenshot:
 
 

TempData["TempModel"] became null but TempData["TempModelKeep"] keeps the data for the next request.
 
 
Now, let's use Peek method in our View. For that declare one string variable and set the TempData Value in it by writing the following code:
  1. @{  
  2.     string msg = TempData.Peek("TempModel").ToString();  
  3. }  
  4. @msg  
Run your application and check the value for TempData["TempModel"].
 


If you read TempData value using Peek then the data will be available for the next request. Use Peek and keep smartly in your application code. 

Summary

  • If you set value for TempData and do not read the value then the data will be available for next request.
  • If you set value for TempData and read in View then the data will be deleted or will be null.
  • If you read TempData in the first request and want to keep the value for the next request then use 'Keep' Method.
  • If you read the TempData using 'Peek' then value persists for the next request also. 
Hope you like this simple article which explains Keep and Peek method.


Similar Articles