In this article I will explain a short tutorial with example on how to use TempData in ASP.Net Core MVC.
TempData is derived from the TempDataDictionary class and is basically a Dictionary object used for passing data from Controller to View or from Controller to Controller.
 
 
What is TempData
1. TempData is derived from the TempDataDictionary class and is basically a Dictionary object i.e. Keys and Values where Keys are String while Values will be objects.
2. Data is stored as Object in TempData.
3. While retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving.
4. TempData can be used for passing value from Controller to View and also from Controller to Controller.
5. TempData is available for Current and Subsequent Requests. It will not be destroyed on redirection.
 
 
TempData Example
In the below example, a string value is set in the TempData object in Controller and it is redirected to another Controller and finally it is displayed in View.
Controller
First Controller
public class FirstController : Controller
{
    public IActionResult Index()
    {
        TempData["Message"] = "Hello MVC Core!";
        return RedirectToAction("Index", "Second");
    }
}
 
Second Controller
public class SecondController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}
 
 
View
View of First Controller
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
</body>
</html>
 
View of Second Controller
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @TempData["Message"]
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: TempData Tutorial with example
 
 
Downloads