Back to: ASP.NET MVC Tutorial For Beginners and Professionals
TempData in ASP.NET MVC Application
In this article, I am going to discuss the significance ofĀ TempData in ASP.NET MVC application with examples. Please read our previous article before proceeding to this article where we discussed ViewModels in the ASP.NET MVC application. As part of this article, we are going to discuss the following pointers which are related to MVC TempData.
- Why do we need TempData in the ASP.NET MVC Application?
- What exactly is TempData in MVC?
- How to use TempData in MVC?
- How to pass and retrieve data from TempData in MVC Application?
- How to retain TempData values in the consecutive request?
Why do we need TempData in the ASP.NET MVC Application?
As we already discussed in our previous articles, we can use ViewData, ViewBag, and strongly typed models to pass the data from a controller action method to a view. Now, we will see another approach to send the data from the controller action method to a view using the TempData.
The limitation of bothĀ ViewData and ViewBag is they are limited to one HTTP request only. So, ifĀ redirection occurs then their values become null means they will lose the data they hold. In many real-time scenarios, we may need to pass the data from one HTTP Request to the next subsequent HTTP Request. For example, we may need to pass the data fromĀ one controller to another controller or one action method to another action method within the same controller. Then in such situations like this, we need to use TempData.
What is TempData in ASP.NET MVC?
The TempData in ASP.NET MVC Framework is one of the mechanisms to pass a small amount of temporary data from a controller action method to a view as well as from a controller action method to another action method either within the same controller or to a different controller. TempData value will become null once the subsequent request is completed by default. But if you want then you can also change this default behavior. If you have a look at the definition Controller class, then you will find the following signature of the TempData property.
As you can see in the above image, the return type of the TempData is TempDataDictionary. Let us see the definition of the TempDataDictionary class.
As you can see the TempDataDictionary class implements the IDictionary interface. So we can say that theĀ TempData in ASP.NET MVCĀ is aĀ dictionary object.Ā As it is a dictionary object, so it is going to store the data in the form ofĀ key-value pairsĀ where eachĀ key must be a stringĀ and the value that we are passing to the dictionary is going to be stored in the form of anĀ objectĀ type.Ā
How to Pass and Retrieve data From TempData in ASP.NET MVC:
The most important point that you need to remember is, as it stores the data in the form of an object so while retrieving the data from TempData type casting is required. If you are accessing string value from the TempData, then it is not required to typecast. But it is mandatory to typecast explicitly to the actual type if you are accessing data other than the string type from the TempData.
Let us understand TempData in ASP.NET MVC with one example.
Modify the Employee Controller as shown below
namespace FirstMVCDemo.Controllers { public class EmployeeController : Controller { public ActionResult Method1() { TempData["Name"] = "Pranaya"; TempData["Age"] = 30; return View(); } public ActionResult Method2() { string Name; int Age; if (TempData.ContainsKey("Name")) Name = TempData["Name"].ToString(); if (TempData.ContainsKey("Age")) Age = int.Parse(TempData["Age"].ToString()); // do something with user Name or Age here return View(); } public ActionResult Method3() { string Name; int Age; if (TempData.ContainsKey("Name")) Name = TempData["Name"].ToString(); if (TempData.ContainsKey("Age")) Age = int.Parse(TempData["Age"].ToString()); // do something with userName or userAge here return View(); } } }
In the above example, we have added data into TempData and accessed the same data using a key inside another action method. Please notice that we have converted values into the appropriate type.
Letās understand TempData
1st Request: http://localhost:xxxxx/Employee/Method1
2nd Request: http://localhost:xxxxx/Employee/Method2
3rd Request: http://localhost:xxxxx/Employee/Method3
As you can see in the above example, we add Name and Age in TempData in the first request, and in the second subsequent request, we access the data from the TempData which we stored in the first request. However, we can’t get the same data in the third request because TempData will be cleared out after the second request.
How to retain TempData values in the consecutive request?
InĀ order to retain the TempData value in the third consecutive request, weĀ need to call TempData.Keep() method.Ā Letās see the use ofĀ TempData.Keep() method Ā with an example
namespace FirstMVCDemo.Controllers { public class EmployeeController : Controller { public ActionResult Method1() { TempData["Name"] = "Pranaya"; TempData["Age"] = 30; return View(); } public ActionResult Method2() { string Name; int Age; if (TempData.ContainsKey("Name")) Name = TempData["Name"].ToString(); if (TempData.ContainsKey("Age")) Age = int.Parse(TempData["Age"].ToString()); TempData.Keep(); // do something with userName or userAge here return View(); } public ActionResult Method3() { string Name; int Age; if (TempData.ContainsKey("Name")) Name = TempData["Name"].ToString(); if (TempData.ContainsKey("Age")) Age = int.Parse(TempData["Age"].ToString()); // do something with userName or userAge here return View(); } } }
There are two overloaded versions of the Keep Method. They are as follows:
- public void Keep(): It will mark all keys in the temp data dictionary for retention.
- public void Keep(string key): It will mark the specified key in the temp data dictionary for retention. Here, the key parameter is the key to retain in the dictionary
In the next article, I am going to discuss Routing in the ASP.NET MVC application. Here, in this article, I try to explain the use of TempData in ASP.NET MVC Application with Examples. I hope this TempData in MVC article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.
awesome explanation
superb explanation
Great article
I’m not able to retain values after using keep() method also.
So used peek(), then worked well
is this article incomplete? I followed it to the letter but when trying to access http://localhost…/Method1 or Mehod2 or Method3 I get an error that the directory cannot be found.
Are you missing the steps to setup Views?
Server Error in ‘/’ Application.
The view ‘Method1’ or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Employee/Method1.aspx
~/Views/Employee/Method1.ascx
~/Views/Shared/Method1.aspx
~/Views/Shared/Method1.ascx
~/Views/Employee/Method1.cshtml
~/Views/Employee/Method1.vbhtml
~/Views/Shared/Method1.cshtml
~/Views/Shared/Method1.vbhtml
Hi,
I’m pretty sure that error is because MVC couldn’t find a corresponding view for your actions
I created the Mehod1,Method2 and coreesponding views Mehtod1.cshtml and method2.cshtml
public ActionResult Method1()
{
TempData[“Name”] = “Pranaya”;
TempData[“Age”] = 30;
return View();
}
public ActionResult Method2()
{
string Name=null;
int Age=0;
if (TempData.ContainsKey(“Name”))
Name = TempData[“Name”].ToString();
if (TempData.ContainsKey(“Age”))
Age = int.Parse(TempData[“Age”].ToString());
ViewBag.Name = Name;
ViewBag.Age = Age;
return View();
}
And in View Method2 body as
@ViewBag.Name
@ViewBag.Age
On Run
1st Request: http://localhost:xxxxx/Employee/Method1 : Shows Data
2nd Request: http://localhost:xxxxx/Employee/Method2 : Not showing (retaining) data.
Please specify what is wrong?
public ActionResult Method1() also need to contains: TempData.Keep();
And what about peek method in TempData?
I think in this tutorial (tempdata) something is missing.
http://localhost:xxxxx/Employee/Method1
this request is cause an error
The view ‘Method1’ or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/employee/Method1.aspx
~/Views/employee/Method1.ascx
~/Views/Shared/Method1.aspx
~/Views/Shared/Method1.ascx
~/Views/employee/Method1.cshtml
~/Views/employee/Method1.vbhtml
~/Views/Shared/Method1.cshtml
~/Views/Shared/Method1.vbhtml
because of missing view page i think…
You have not mentioned about peek() method in this article
You forgot to explain about Peek
This article is incomplete, It makes us difficult to understand.
Kindly tell the lateral steps on how to access the tempdata in view etc.
I request you to please Complete the article.
The way you are accessing the Data from ViewBag and ViewData, in the same way only, you can access the data from the TempData within a View.