TempData in Asp.net MVC3 Razor



1. TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.

2. TempData is used to pass data from current request to subsequent request means incase of redirection.
3. Typecasting is required for complex data types.
4. It is used to store only one time messages like error message, validation message.

Watch Video


Following is the way we use TempData :




In the above screenshot we are fetching form data using FormCollection i.e FirstName and we are storing that in TempData.


After assigning TempData in the controller, we can access its value in View, like ViewBag and ViewData.



After Running the Application :



After running the application, view asks to enter the FirstName, we enter it and press Submit.




We get the FirstName from FormCollection and assign it to TempData with key name FirstName and we will render this in the view.







Finally the FirstName gets rendered on the view. This is how we use TempData.


Points To Remember :

1. TempData works similar to ViewBag and ViewData, but its data persist for subsequent request.
2. ViewData and ViewBag data persists only for single call to controller. In the next call, it becomes null.
3. TempData persists value for subsequent call to controller i.e one more than ViewBag and ViewData.
4. TempData has advantage over ViewBag and ViewData just becomes its data persists for subsequent call to controller.

0 comments:

Post a Comment