Using Peek And Keep In TempData In ASP.NET MVC

In a previous article, we discussed State Management in ASP.NET MVC using ViewData, ViewBag, TempData, and Sessions. However, TempData has more capabilities than what we discussed.

Now, let’s understand TempData.

TempData is used to pass the data from Action to Action or Controller to Controller, and then to View. In the case of Action to Action or Controller to Controller, ViewData, and ViewBag do not persist the data. It keeps the information for a single HTTP Request. It is derived from TemDataDictionary and along with this, it requires typecasting for complex data types and requires a null check to void exceptions.

As per the above explanation, TempData maintains the data throughout a single request; however, it can persist the data for the next request also, which are described for the below conditions.

  • Not Read: If the value of TempData is not read, then it will persist that data for the next request. In other words, suppose we are storing the data in TempData, say TempData[“CurrTime”]= DateTime. Now, if we do not read it on View, then for the next request, the value of TempData[“CurrTime”] will remain the same.
  • Read and Keep: If we have read the value of TempData and use keep(), then it will persist for the next request. Let's understand the below example.

In-Home Controller

public ActionResult Index()
{
    TempData["CurrTime"] = DateTime.Now;
    return View();
}

In Idex. cshtml

@TempData["CurrTime"];
@{ TempData.Keep("CurrTime"); }

Now, in the above example, we have assigned the value to TempData[“CurrTime”] in the Index action method. And we are reading its value in View, i.e., Index. cshtml. Along with that, we have used TempData.

Now, go to the Index action method, keep the breakpoint, and refresh the browser by pressing F5. You get the previous value of TempData.

Peek and Read

If we read the value of TempData by using the Peek method, then its value will persist for the next request.

Let's understand this via the below example.

In-Home Controller

public ActionResult Index()
{
    TempData["CurrTime"] = DateTime.Now;
    return View();
}

In Idex. cshtml

@{  
    String currTime = TempData.Peek("CurrTime").ToString();  
}  
@currTime;

Now, in the above example, we have assigned the value to TempData[“CurrTime”] in the Index action method. And we are reading its value by TempData.Peek (“CurrTime”) in View, i.e., Index. cshtml. which will persist the data present in it for the next request.

Now, go to the Index action method, keep the breakpoint, and refresh the browser by pressing F5. You will get the previous value of TempData.

Now, take a scenario where you want to persist the data for only several requests and after that, you do not want to use it. In this case, you must use TempData. However, if you want to store it for all requests, then use Sessions.


Similar Articles