How to Persist Data with TempData using Peek and Keep in MVC

In this post we are going to discuss about how to preserve the value in next request using TempData Peek and Keep in 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”];
var readInfo = TempData[“dotnet-helpers-info”];

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