Over a million developers have joined DZone.



ASP.NET MVC offers  three options ViewData, ViewBag and TempData for passing data from controller to view and in next request. TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value.

The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. NOTE : Once the value of TempData is read , it is cleared out. NOTE: TempData is session under the hood, hence they're not entirely different. However, the difference is that TempData is for redirects, and redirects only. So when you set some messages in TempData and then redirect, you are using TempData correctly

Hence Session is not advisable for such scenario which we were commonly used to in the ASP.NET WEBFORM world. e.g var data =(Student)TempData["StudentRecord"];
 Based on this reading from  TempData["StudentRecord"] subsequent call to TempData["StudentRecord"] is null.

The next question will be how do we make TempData retain it's values even if it is read from , making it work as a Session variable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApi_Demo.Controllers
    public class HomeController : Controller
 // Action where record is stored in the TempData
        public ActionResult Index()
            var student = new Student() { Name = "Ade Yinka",Sex = "Male" , Age = 25};
 // this prevent values loss after reading from the TempData

            TempData["Student"] = student;

            return View();

 // Action where we retrieve the values/object stored in the TempData
        public ActionResult Register()
 // prevent loss if we redirect back to this action again

            var studentRecord = (Student)TempData["Student"];

            return View();

Hence our Tempdata no longer loses it values even after we read from it.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}