×

iFour Logo

Tempdata in MVC

Kapil Panchal - June 16, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Tempdata in MVC

TempData is used to transfer data from the view to the controller, the controller to the view, or from an action method to another action method of the same or a different controller.

TempData temporarily saves data and deletes it automatically after a value is recovered.

 

Table of Content

TempData is owned by the ControllerBase class. This means it is available in any controller or view in the ASP.NET MVC application.

TempData is also a dictionary object, which comes from TempDataDictionary and stores the data in the key-value pair.

TempData can be used in a couple of scenarios.


  1. Passing Data from Controller to View.
  2. Transmit data from one activity to another.

Moreover, unlike ViewBag and ViewData TempData can hold the value for several successive queries. Here are some important things we should keep in mind when using TempData.

A one-stop solution to hire WPF developer for your esteemed business.

  1. Type Casting for complex types is necessary.
  2. Checking for null is required.
  3. Due to boxing and unboxing, unnecessary use of it must be avoided.
  4. No intelligence.
  • It is used for storing data between two sequential queries.
  • During the redirect, the values of TempData will be maintained. It is similar to a session, which is brief, and uses an internal session to store data.
  • We can use the loop to access each key and its value sent to the server. Let's add the following method.
  • To prevent execution time errors, check the NULL values.
  • Temporary data is mainly used in messages like error messages or validation messages which store a time message.
  • To supply all values of the template in a third request, we can use Call TempData.Keep()

Why is TempData required in the ASP.NET MVC application?


As we discussed previously in our previous articles, we can use ViewData, ViewBag, and a heavily typed template to pass data from a controller action method to a view. Now, we will see another approach to send controller action method data to a view with TempData.

The restriction in ViewData and ViewBag is that they are limited to a single HTTP request. Thus, if the redirect happens, their values become zero, which will lose the data they hold. In many real-time scenarios, we may need to transmit data from one HTTP request to another. For instance, it may be necessary to pass data from one controller to another controller or from one action method to another action method within the same controller. In situations such as these, TempData should be used.

What is TempData in MVC?


The TempData in ASP.NET MVC is a mechanism for transmitting a small amount of temporary data from one controller to one view and one controller method of action to another method of action either inside the same controller or with another controller. The value of TempData will be null when the next query is completed by default. But if you want, you can change that default behavior too. If you look at the definition of the Controller class, you will find the next signature of the TempData property.

  Public TempDataDictionary TempData {get; set;}
              

As you can see in the image above, the TempData feedback type is TempDataDictionary. Let's look at how TempData Dictionary is defined.

  Public class TempDataDictionary : IDictionary

              

As shown, the TempDataDictionary class implements the IDictionary interface. It is, therefore, possible to say that TempData in ASP.NET MVC is a dictionary object. Because it is a dictionary object, it will store the data the shape of the key-value pairs into which each key is to be a string, and the value we transmit to the dictionary will be stored as a type of object.

How to transfer and retrieve TempData data into ASP.NET MVC:


The most important thing you should remember is because it stores data in the form of an object thus while recovering data from TempData type casting is necessary. If you access the channel value from TempData, it is not necessary to type. But it is compulsory to explicitly type to the current type if you access data other than the string type from TempData.

Let's try to figure out TempData in MVC using an example.

Amend the Student Controllers as outlined below.

 namespace MVCDemo.Controllers
  {
   public class StudentController : Controller
   {
    public ActionResult Method1()
     {
      TempData["Name"] = "Ifour";
      TempData["Age"] = 21;
      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()) 
        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()); 
            return View();
         }
      }
 }
           

In the above example, we added data to TempData and accessed the same data using one key in another action method. Please note that the values have been converted into the appropriate type.

Let's see if we can figure out TempData.

1st Request: http://localhost:xxxxx/ Student /Method1

2nd Request: http://localhost:xxxxx/ Student /Method2

3rd Request: http://localhost:xxxxx/ Student /Method3

As you can see in the example above, we include Name and Age in TempData in the first query and in the second following query, we access the data from the TempData we stored in the first query. However, we cannot obtain the same data in the third query as TempData will be deleted after the second query.

Looking for Trusted Dot Net Development Company ? Your Search ends here.

 

How do I keep the TempData values in the consecutive statement?


To keep TempData in the third consecutive query, we have to call the TempData.Keep() method. Let's talk about how to use TempData.Keep() method with an example.

namespace MVCDemo.Controllers
{
   public class StudentController : Controller
{
public ActionResult Method1()
{
TempData["Name"] = "Ifour";
TempData["Age"] = 21;
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();
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());
  return View();
   }
 }
}
             

 

Conclusion: TempData in MVC


To sum up, we use TempData to store the data and access it in subsequent queries. Internally, it utilizes the session. Its type is TempData Dictionary. It is automatically deleted after the following queries and we must manually delete the session variable. We can also use TempData when dealing with controllers. We have to run TempData and ViewData both ways before we consume them in our action or view. And the last suggestion is, just use ViewBag, ViewData, TempData when you actually need it. If you can complete your task with other best techniques and then proceed with these techniques like ViewModel is the alternative option to ViewBag and ViewData.

Tempdata in MVC TempData is used to transfer data from the view to the controller, the controller to the view, or from an action method to another action method of the same or a different controller. TempData temporarily saves data and deletes it automatically after a value is recovered.   Table of Content 1. TempData can be used in a couple of scenarios. 2. Why is TempData required in the ASP.NET MVC application? 3. What is TempData in MVC? 4. How to transfer and retrieve TempData data into ASP.NET MVC 5. How do I keep the TempData values in the consecutive statement? 6. Conclusion: TempData in MVC TempData is owned by the ControllerBase class. This means it is available in any controller or view in the ASP.NET MVC application. TempData is also a dictionary object, which comes from TempDataDictionary and stores the data in the key-value pair. TempData can be used in a couple of scenarios. Passing Data from Controller to View. Transmit data from one activity to another. Moreover, unlike ViewBag and ViewData TempData can hold the value for several successive queries. Here are some important things we should keep in mind when using TempData. A one-stop solution to hire WPF developer for your esteemed business. Contact us Type Casting for complex types is necessary. Checking for null is required. Due to boxing and unboxing, unnecessary use of it must be avoided. No intelligence. It is used for storing data between two sequential queries. During the redirect, the values of TempData will be maintained. It is similar to a session, which is brief, and uses an internal session to store data. We can use the loop to access each key and its value sent to the server. Let's add the following method. To prevent execution time errors, check the NULL values. Temporary data is mainly used in messages like error messages or validation messages which store a time message. To supply all values of the template in a third request, we can use Call TempData.Keep() Why is TempData required in the ASP.NET MVC application? As we discussed previously in our previous articles, we can use ViewData, ViewBag, and a heavily typed template to pass data from a controller action method to a view. Now, we will see another approach to send controller action method data to a view with TempData. The restriction in ViewData and ViewBag is that they are limited to a single HTTP request. Thus, if the redirect happens, their values become zero, which will lose the data they hold. In many real-time scenarios, we may need to transmit data from one HTTP request to another. For instance, it may be necessary to pass data from one controller to another controller or from one action method to another action method within the same controller. In situations such as these, TempData should be used. Read More: Overloading Action Method In Asp.net Mvc What is TempData in MVC? The TempData in ASP.NET MVC is a mechanism for transmitting a small amount of temporary data from one controller to one view and one controller method of action to another method of action either inside the same controller or with another controller. The value of TempData will be null when the next query is completed by default. But if you want, you can change that default behavior too. If you look at the definition of the Controller class, you will find the next signature of the TempData property. Public TempDataDictionary TempData {get; set;} As you can see in the image above, the TempData feedback type is TempDataDictionary. Let's look at how TempData Dictionary is defined. Public class TempDataDictionary : IDictionary As shown, the TempDataDictionary class implements the IDictionary interface. It is, therefore, possible to say that TempData in ASP.NET MVC is a dictionary object. Because it is a dictionary object, it will store the data the shape of the key-value pairs into which each key is to be a string, and the value we transmit to the dictionary will be stored as a type of object. How to transfer and retrieve TempData data into ASP.NET MVC: The most important thing you should remember is because it stores data in the form of an object thus while recovering data from TempData type casting is necessary. If you access the channel value from TempData, it is not necessary to type. But it is compulsory to explicitly type to the current type if you access data other than the string type from TempData. Let's try to figure out TempData in MVC using an example. Amend the Student Controllers as outlined below. namespace MVCDemo.Controllers { public class StudentController : Controller { public ActionResult Method1() { TempData["Name"] = "Ifour"; TempData["Age"] = 21; 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()) 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()); return View(); } } } In the above example, we added data to TempData and accessed the same data using one key in another action method. Please note that the values have been converted into the appropriate type. Let's see if we can figure out TempData. 1st Request: http://localhost:xxxxx/ Student /Method1 2nd Request: http://localhost:xxxxx/ Student /Method2 3rd Request: http://localhost:xxxxx/ Student /Method3 As you can see in the example above, we include Name and Age in TempData in the first query and in the second following query, we access the data from the TempData we stored in the first query. However, we cannot obtain the same data in the third query as TempData will be deleted after the second query. Looking for Trusted Dot Net Development Company ? Your Search ends here. See here   How do I keep the TempData values in the consecutive statement? To keep TempData in the third consecutive query, we have to call the TempData.Keep() method. Let's talk about how to use TempData.Keep() method with an example. namespace MVCDemo.Controllers { public class StudentController : Controller { public ActionResult Method1() { TempData["Name"] = "Ifour"; TempData["Age"] = 21; 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(); 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()); return View(); } } }   Conclusion: TempData in MVC To sum up, we use TempData to store the data and access it in subsequent queries. Internally, it utilizes the session. Its type is TempData Dictionary. It is automatically deleted after the following queries and we must manually delete the session variable. We can also use TempData when dealing with controllers. We have to run TempData and ViewData both ways before we consume them in our action or view. And the last suggestion is, just use ViewBag, ViewData, TempData when you actually need it. If you can complete your task with other best techniques and then proceed with these techniques like ViewModel is the alternative option to ViewBag and ViewData.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
HR Analytics Dashboard – Key Metrics & Examples
HR Analytics Dashboard – Key Metrics & Examples

HR analytics, generally known as People Analytics, could be a solid answer to those sceptics who believe that the HR department's role is just about hiring and making offers! This...

10 Executive Dashboard Examples for Consultants and CEOs
10 Executive Dashboard Examples for Consultants and CEOs

There is a principle behind every business. “If you don’t keep track of essentials, you won’t get clear direction, eventually causing your company to stumble.” To manage this scenario,...

How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...