Holi Sale. Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Browse Tutorials

02 Intermediate

Persisting Data with TempData

Persisting Data with TempData

05 Mar 2024
Intermediate
189K Views
1 min read

TempData is used to pass data from current request to subsequent request (means redirecting from one page to another). It’s life is very short and lies only till the target view is fully loaded. But you can persist data in TempData by calling Keep() method.

TempData with Keep method

If you want to keep value in TempData object after request completion, you need to call Keep method with in the current action. There are two overloaded Keep methods to retains value after current request completion.
  1. void Keep()

    Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.

     @model MyProject.Models.EmpModel;
    @{ 
     Layout = "~/Views/Shared/_Layout.cshtml"; 
     ViewBag.Title = "About";
     var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting 
     TempData.Keep(); // retains all strings values 
    } 
  2. void Keep(string key)

    Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.

     @model MyProject.Models.EmpModel;
    @{ 
     Layout = "~/Views/Shared/_Layout.cshtml"; 
     ViewBag.Title = "About";
     var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting 
     TempData.Keep("emp"); // retains only "emp" string values 
    } 

Key point about TempData and TempData.Keep()

  1. Items in TempData will only tagged for deletion after they have read.

  2. Items in TempData can be untagged by calling TempData.Keep(key).

  3. RedirectResult and RedirectToRouteResult always calls TempData.Keep() to retain items in TempData.

Summary

In this article you have learned how to persist data in TempData. I hope you will refer this article for your need. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this