This blog assumes you have an idea of MVC. If not, I would suggest starting from this youtube video Learn MVC.
Recently, I was taking MVC class in Mumbai and I saw there was a lot of confusion among participants on how MVC tempdata, Peek and Keep works. I think the confusion stems because most of the MVC developers know only the half truth.
So the half thing which most of the MVC developers 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 sends a request to an 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();
The above image i have taken from http://stepbystepschools.net/?p=1810
So if you register these four conditions in your mind, you should not have any confusion around
Below is a video which demonstrates