Difference between TempData keep() And Peek() in Asp.Net MVC

Introduction :

TempData helps to maintain data when we want to transfer data from one action method to another action method of the same or a different controller as well as redirects.

I have already discussed what is TempData and why and when to use TempData in previous article .

Now learn what is difference between TempData keep() and TempData peek().

TempData keep() Mehod Example:

Controller  Action Method:

       public ActionResult About()
        {
            TempData["KeepMessage"]= "TempData keep() Example in MVC";

            return View();
        }

View :

    @TempData[“KeepMessage“]

@{     TempData.Keep(“KeepMessage“);   } /

 

Keep() method marks the specified key in the dictionary for retention

You can use Keep() when prevent/hold the value depends on additional logic.

when you read TempData once and want to hold data for next request then use keep method, so TempData can available for next request as above example.

TempData Peek() Mehod Example:

Controller  Action Method:

        public ActionResult About()
        {
            TempData["peekMessage"] = "TempData Peek() Example in MVC";

            return View();
        }

View :

     @TempData.Peek(“PeekMessage“)

 

Peek() method returns an object that contains the element that is associated with the specified key, without marking the key for deletion

Using Peek method both the operation of accessing and persisting value is done in a single Call/statement.

Using Tempdata peek method we can perform read and hold data for next request in single call.

 

Conclusion :
keep method is used when need to hold data for next request, by using peek method we can read and hold data for next request  in single call.

 

Learn More Tutorial

9 Comments

Leave a Reply

Your email address will not be published.