Sunday, September 14, 2014

MVC Tempdata , Peek and Keep confusion

This blog assumes you have idea on MVC in case not I would suggest starting from thisyoutube video Learn MVC.

Recently I was taking MVC class in Mumbai and I saw there was lot of confusion among participantson how MVC tempdata , Peek and Keep works. I think the confusion stems because most of the MVC developers know only thehalf truth.

So the half thing which most of MVC developer know is:-

“Tempdata helps to preserve values for a single request”.

The other half-truth which developers do not know is or I will say which confuses developer is:-

“TempData CAN ALSO preserve values for the next request depending on 4 conditions”.

So let us try to understand the above two statements. When an end user send’s a request to a MVC application “TempData” is maintained throughout the complete request. This request can traverse through multiple actions or controllers until it displays the view on the browser.

Now in the same session (without closing the browser) if a new / second request is initiated then “TempData” will be persisted depending on 4 CONDITIONS:-

  • Not Read.
  • Normal Read.
  • Read and Keep.
  • Peek and Read.

So let’s discuss these four conditions in more detail ( Do see the below diagram for better understanding ):-

Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.

Condition 2  ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.

stringstr = TempData[“MyData”];

Even if you are displaying it’s a normal read like the code below.


Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.


Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.

stringstr = TempData.Peek("Td").ToString();

So if you register these four condition’s in your mind you should not have any confusion’s around TempData:) .

1 comment:

Anil Singh said...

Nice collection!! I like it.