In this post we are going to discuss about how to preserve the value in next request using TempData Peek and Keep in ASP.NET MVC.

What is TempData?

Tempdata helps to store/preserve values within in a single request. This is the one of the concept for maintaining state in ASP .Net MVC.

How to store/persist data in next request?

TempData preserve values for the next request in 4 different conditions in MVC.ย They are

  • Condition 1 – Not Read in First Request.
  • Condition 2 – Read In First Request.
  • Condition 3 – Read & persist using Keep.
  • Condition 4 – Persist using Peek and Read.

Let usย discuss this one by one in detail.

Not Read in First Requestย :ย If we do not read “TempData” in the current request then โ€œTempDataโ€ value will be persisted for the next request.
Read In First Request :ย If we read “TempData” in the current request then โ€œTempDataโ€ value will be not persist for the next request.
Read & Persist using Keep :ย If we read “TempData” in the current request and we canย keep method to persist TempData for the next request. In MVC, we are having void keep() and ย void keep(string key) methods toย persist the data.

Example :

var readInfo = TempData

[“dotnet-helpers-info”];
TempData.Keep(“dotnet-helpers-info”);
OR
var readInfo = TempData[“dotnet-helpers-info”];
TempData.Keep();

Persist using Peek and Read :ย If we read “TempData” using the Peek method then then the data will persist in the next request.

Example :

var readInfo = TempData.Peek(“dotnet-helpers-info”);

Flow Chart

https://dotnet-helpers.com/wp-content/uploads/2015/11/TempdatawithKEEPandPEEK-Dotnet-helpers.com-1-1.jpg