TempData, Peek And Keep In ASP.NET MVC

 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. 
  • 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. 
In Short we can say that 

temdata uses TempDataDictionary where every data read, will be marked as available for deletion, keep() and peek() both are used to retain data, the only difference is, keep() will be used to retain data that has been marked for deletion (Read and Keep), whereas peek() will be used where you want to read data without marking it for deletion. 


@TempData["MyData"]; TempData.Keep("MyData");
here we are reading it first after that unmarking it using 

keep.stringstr = TempData.Peek("Td").ToString();
here we are reading without marking it for deletion.

Hope you like this simple article which explains Keep and Peek method.

Share this

Related Posts

Next Post »