What is TempData in MVC?

Category: C SharpWhat is TempData in MVC?
Editor">Editor Staff asked 2 years ago

What is TempData in MVC?

1 Answers
Editor">Editor Staff answered 2 years ago

TempData is a dictionary object to store data temporarily. It is a TempDataDictionary class type and instance property of the Controller base class.
 
TempData is able to keep data for the duration of a HTP request, in other words it can keep live data between two consecutive HTTP requests. It will help us to pass the state between action methods. TempData only works with the current and subsequent request. TempData uses a session variable to store the data. TempData Requires type casting when used to retrieve data.
 
TempDataDictionary is inherited from the IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>> and IEnumerable interfaces.
 
Example

 

  1. public ActionResult FirstRequest()  
  2. {  
  3.     List < string > TempDataTest = new List < string > ();  
  4.     TempDataTest.Add(“Tejas”);  
  5.     TempDataTest.Add(“Jignesh”);  
  6.     TempDataTest.Add(“Rakesh”);  
  7.     TempData[“EmpName”] = TempDataTest;  
  8.     return View();  
  9. }  
  10. public ActionResult ConsecutiveRequest()   
  11. {  
  12.     List < string > modelData = TempData[“EmpName”as List < string > ;  
  13.     TempData.Keep();  
  14.     return View(modelData);  
  15. }