Tuesday, July 12, 2016

TempData , Peek and Keep ASP.NET MVC

 What is need of "TempData" ?

TempData helps to preserve data throughout the current request. The request can travel through action to action or controller to controller until the view is displayed.

What is difference between TempData and ViewData ?

"TempData" maintains data for the complete request while "ViewData" maintains data only from Controller to the view.

Does "TempData" preserve data in the next request also?

"TempData" is available through out for the current request and in the subsequent request it's available depending on whether "TempData" is read or not.

So if "TempData" is once read it will not be available in the subsequent request.

What is the use of Keep and Peek in "TempData"?

Once "TempData" is read in the current request it's not available in the subsequent request. If we want "TempData" to be read and also available in the subsequent request then after reading we need to call "Keep" method as shown in the code below.

@TempData["MyData"];
TempData.Keep("MyData");

The more shortcut way of achieving the same is by using "Peek". This function helps to read as well advices MVC to maintain "TempData" for the subsequent request.

string str = TempData.Peek("Td").ToString();

No comments :

Post a Comment