DEV Community

Cover image for What is Tempdata and How to Use in MVC?
Tarun Gurang
Tarun Gurang

Posted on • Originally published at ifourtechnolab.com

What is Tempdata and How to Use 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.

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.

  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.
  • The value of Tempdata must already be entered while using it.
  • 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 does TempData on 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;}

Enter fullscreen mode Exit fullscreen mode

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<string, object="">
</string,>

Enter fullscreen mode Exit fullscreen mode

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();
}
}
}

Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}

Enter fullscreen mode Exit fullscreen mode
Conclusion

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.

Discussion (0)