In this article I will explain with an example, how to use TempData in ASP.Net MVC.
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 of String type while Values will be objects.
2. Data is stored as Object in TempData.
3. While retrieving, the data 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.
Example
Controllers
First Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, a string value is set in the TempData object and redirected to another Controller (SecondController) using RedirectResult method of RedirectResult class.
public class FirstController : Controller
{
// GET: First
public ActionResult Index()
{
TempData["Message"] = "Hello MVC!";
return new RedirectResult(@"~\Second\");
}
}
Second Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class SecondController : Controller
{
// GET: Second
public ActionResult Index()
{
return View();
}
}
View
First Controller
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
</div>
</body>
</html>
Second Controller
Inside the View, the TempData object is used to display the message which redirected from another Controller.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@TempData["Message"]
</div>
</body>
</html>
Screenshot
Downloads
Download Code