TempData
used to transfer data between controllers or between actions. There is one
point to note that TempData is only work during the current and subsequent
request and it is generally used to store one time message.
But one
can persist data in TempData object even after request completion with the help
of Keep() or Peek() method.
TempData.Keep(): TempData.Keep() method keep value
in TemData object at the end of current request. There are two overloaded keep
methods available with TempData:
·
void Keep(): This method make ensures that all
the items in TempData are not destroyed on current request completion.
·
void Keep(string key): One can persist the specific item
in TempData by passing in the item name.
TempData.Peek(string key): It returns an object that contains
the element that is associated with the specified key, without marking the key
for deletion.
Example:
//Set some value to TempData
TempData["value"] = "some
value";
//Get value from TempData and marking TempData for
deletion.
var val = TempData["value"];
//Decide to retain the value.
//Keep all items.
TempData.Keep();
//Keep specific item named as value.
TempData.Keep("value");
//Read and retain value at the end of the request in a
single request using Peek.
val = TempData.Peek("value");
|
Difference between Keep() and Peek()
method: Both method
used to retain the value at the end of request and if you are wondering what is
the difference then here it is:
Keep Method
|
Peek Mthod
|
To read
and retain the value with Keep one need to do two request, i.e. first read
the value and in next statement call Keep method to retain value.
|
With
the help of Peek method one can do both operation in a single statement i.e.
access as well retain value.
|
Keep
method can be overloaded, i.e. one can keep all items or pass the key to
retain specific item.
|
There
is no overloaded method in case of Peek method.
|
RedirectResult
and RedirectToRouteResult internally calls Keep method to retain items
|
Peek
method is not called internally with any of ActionResult.
|
Great article. I have explained the same with a flow diagram here http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion
ReplyDeleteIt might help to other
ReplyDeletehttp://stackoverflow.com/a/27242685/3930005
nice
ReplyDeletenmuo9lol
ReplyDeleteGood Concept..
ReplyDelete