Data Haunting

Easy Solutions Destination


Persisting Data With TempData

TempData is used to pass data from Controller(Action) to Controller(Action) means one current request to subsequent request(from one page to another page). In this article we will discuss how to persist data with TempData using Keep and Peek method as well we will also see the difference between Keep and Peek method.

If you have any question like what is TempData than you can refer our recently released article What is ViewBag, ViewData and TempData in MVC. In this article we will discuss only how to persist and maintain TempData with Keep and Peek method.

Persist TempData with Keep method

We can save TempData value using keep method after reading value from TempData. There are two overload for Keep method.

  1. Void Keep()
  2. This method you can use when all items in TempData you want to retain and does not allow deletio forn any TempData’s items.

  3. Void Keep(string Key)
  4. This method you can use when particular TempData’s value you want to persist and does not allow deletion for that particular TempData’s value.

Persist TempData with Peek method

We can persist TempData value using also Peek method. If we use Peek method than TempData automatically persist Data for next Request.

According to above method(Peek method) is shortest and better way to persist TempData Value.

Difference and when to use Keep and Peek Method

According to MSDN

Keep(): – marks the specified key in the dictionary for retention.

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

In short when an object in a TempDataDictionary is read, it is marked for deletion but we can use Keep and Peek method to save Data with TempData. See the Difference between Peek and Keep method.

Keep method Peek method
Once we retrieved value from object than it is marked for deletion, with Keep method we can later save object from Deletion. With Peek method we can persist TempData value without marking for deletion in a single call.
Use Keep when you want to save particular TempData on condition based or you want save all TempData’s value. Use Peek method when you want to save particular TempaData’s value always.

What is your opinion ?

Here we have seen how to retain Data with TempData using Peek and Keep method. I hope this article also be useful to understand difference between Peek and Keep method. If you have any query you can comment or you can mail me.

Leave a Reply