So, TempData can be used to maintain data between oneĬontroller action to the other controller action. TempData is also a dictionary object that stays for the time of an string str = TempData.Peek("Td").ToString() 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request. 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted. string str = TempData Įven if you are displaying it’s a normal read like the code below. If we understand these 4 points you would see more clarity.Below is a diagram with all 4 conditions, read the third and fourth point which talks about Peek and Keep.Ĭondition 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.Ĭondition 2 ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request. Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”. You can watch this video which explains the Keep and Peek with demonstration The confusion arises becauses TempData behaves differently under different condition. Just finished understanding Peek and Keep and had same confusion initially. You have 2 good questions about how TempData works here and here Use Keep when retaining the value depends on additional logic. You can use Peek when you always want to retain the value for another request. See msdn //second request, get value marking it from deletion Retrieving the object and later on saving it from deletion are 2 different calls. With Keep you specify a key that was marked for deletion that you want to keep. third request, read value and mark it for deletion With Peek you get the value without marking it for deletion with a single call, see msdn: //second request, PEEK value so it is not deleted at the end of the request Say we get back to the first request where the value was saved to TempData. The Peek and Keep methods allow you to read the value without marking it for deletion. third request, value is not there as it was deleted at the end of the second request That means if you put something on TempData like TempData = "someValueForNextRequest" Īnd on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion: //second request, read value and is marked for deletion When an object in a TempDataDictionary is read, it will be marked for deletion at the end of that request.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |