TempData in MVC

TempData used to store temporary data which can be used in the subsequent request by the user. TempData will be cleared out after the completion of a subsequent request.

TempData is useful when you want to transfer non-sensitive data from one action method to another action method of the same or a different controller as well as redirects. It is dictionary type which is derived from TempDictionary.

Adding a key-value pair in TempData as shown in the below example.

Example: TempData

public class AventController : Controller
{
    // GET: Student
    public AventController()
    {

    }
    public ActionResult Index()
    {
        TempData["name"] = "Test data";
        TempData["age"] = 30;

        return View();
    }

    public ActionResult About()
    {
        string userName;
        int userAge;
        
        if(TempData.ContainsKey("name"))
            userName = TempData["name"].ToString();
    
        if(TempData.ContainsKey("age"))
            userAge = int.Parse(TempData["age"].ToString());
    
        // do something with userName or userAge here 

        return View();
    }
}

In the above code, we added data into TempData and accessed the same data using a key inside another action method. Notice that we have converted values into the appropriate type.

 

As you can see in the above example, we add test data in TempData in the first request and in the second subsequent request we access test data from TempData which we stored in the first request. However, you can’t get the same data in the third request because TempData will be cleared out after second request.

Call TempData.Keep() to retain TempData values in a third consecutive request.

Example: TempData.Keep()

public class AventController : Controller
{
    // GET: Student
    public AventController()
    {

    }
    public ActionResult Index()
    {
        TempData["myData"] = "Test data";
        return View();
    }

    public ActionResult About()
    {
        string data;
        
        if(TempData["myData"] != null)
            data = TempData["myData"] as string;
        
        TempData.Keep();
        
        return View();
    }

    public ActionResult Contact()
    {
        string data;
        
        if(TempData["myData"] != null)
            data = TempData["myData"] as string;
            
        return View();
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *