
As an ASP.Net MVC developer, you may frequently be involved with terms like Tempdata, viewdata, and viewbag. In this post, I’m going to take a close look atTempData and how it works. You can also read this same article in my blog. If you want to read the difference between Viewbag, ViewData, and Tempdata then read it from my blog post.
For explanation purposes, I’m going to create a small MVC project with 3 views and a controller.
- Index.cshtml This is the default view, which is loaded by the default action method.
- Page1.cshtml This is another view, called a redirect.
- Page2.cshtml Yet another view, called by redirect
The controller is named as.
DefaultController.cs
TempData
We will start with TempData.As a first step, I will set the value of TempData in the Action method “Index”, like below.
using System.Web.Mvc;
namespace SessionHandlingInMVC.Controllers
{
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
TempData["MyTempDataValue"] = "Value initialized in Index Action Method";
return View();
}
public ActionResult Page1()
{
return View("Page1");
}
public ActionResult Page2()
{
return View("Page2");
}
}
}
In the “Index” view, we can get the value of the initialized “Tempdata” value as below.
<h2>Index Page</h2>
<p>
@{
string strTempDataValue = (string)TempData["MyTempDataValue"];
}
@strTempDataValue
</p>
Please take a close look at how the value is retrieved from the “TempData”.You can’t directly assign to it the specific type. A typecasting is needed when you retrieve the value from Tempdata. The above snippet just gets the value from TempData dictionary and prints it on.
In the next snippet, I’m going to change the above snippet a little bit like below.
<h2>Index Page</h2>
<p>
@{
string strTempDataValue = (string)TempData["MyTempDataValue"];
}
@strTempDataValue
@{
string strAnotherRead = (string)TempData["MyTempDataValue"];
}
@strAnotherRead
</p>
In the above snippet, we have read the TempData value twice. As a result the value is also printed twice in the view.

The above result confirms that you can read the TempData value inside the current request in as much time as possible.
In the following snippet, I’m going to read the value of the TempData in the next view, which is rendered by the action method “Page1”.
<h2>Page1</h2>
<p>
@{
string strTempDataValueInPage1 = (string)TempData["MyTempDataValue"];
}
@strTempDataValueInPage1
</p>




Madhanmohan DevarajanPosted Oct 18, 2016, 10:57 AM
Good one.
Damodara NaiduPosted Oct 18, 2016, 12:40 AM
Nicely Explained.
Shamim UddinPosted Oct 17, 2016, 11:45 PM
Nice