
 August 7, 2020 13:02 by 
 Peter
 PeterIn this  Article, we will discuss about TempData. TempData in ASP.NET MVC can be  used to store temporary data which can be used in the subsequent  request. TempData will be cleared out after the completion of a  subsequent request.
TempData  is useful when you want to transfer non-sensitive data from one action  method to another action method of the same or a different controller as  well as redirects. It is dictionary type which is derived from  TempDataDictionary.
You can add a key-value pair in TempData as shown in the below example.
TempData  allows you to store data & it will remain after redirects. It uses  the Session to store data. When an object in a TempDataDictionary. It  will be marked for deletion at the end of that request.
TempData declared as
TempData["value"] = "data";
Example
public ActionResult FirstAction()
{
    // store something into the tempdata that will be available during a single redirect
    TempData["FirstAction"] = "SecondAction";
    // you should always redirect if you store something into TempData to
    // a controller action that will consume this data
    return RedirectToAction("SecondAction");
}
public ActionResult SecondAction()
{    var data = TempData["FirstAction"];
   return View();
}
 
The  Peek and Keep methods allow to read the value without deletion. we can  say that first request data will remains in TempData. You can use Peek  when you always want to retain the value for another request. Use Keep  when retaining the value depends on additional logic. 
//second request, Peek value is not deleted at the end of the request
object value = TempData.Peek("value");
//third request, read value and delete
object value = TempData["value"];
 
Keep
//second request, get value going for delete
object value = TempData.["value"];
//later  decide to keep it for next request
TempData.Keep("value");
//third request, read value and mark it for deletion
object value = TempData["value"];
Removing TempData
TempData.Clear() : It is use to remove all keys from the TempDataDictionary TempData.Remove(key) :Remove a specific key from TempDataDictionary.
Note:  Since TempData makes use of the Session State behavior, it must be  enabled on the controller using TempData. By default it is always  enabled, You can disable session state for your controllers by adding [SessionState(SessionStateBehavior.Disabled)] attribute.
HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu  is European Windows Hosting Provider which focuses on Windows Platform  only. We deliver on-demand hosting solutions including Shared hosting,  Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service  for companies of all sizes. We have customers from around the globe,  spread across every continent. We serve the hosting needs of the  business and professional, government and nonprofit, entertainment and  personal use market segments.
