TempData is another dictionary object for storing data using key-value, in this post we learn how to use TempData in Asp.net MVC application.
TempData is a dictionary object derived from TempDataDictionary, which can contain key-value pairs, useful for transferring data from controller to view in ASP.NET MVC Application, TempData stays for a subsequent HTTP Request as opposed to other options ( ViewBag and Viewdata ) those stay only for current request.
So "TempData value stays for a subsequent HTTP Request" what does that mean?
Here we have created a small form with simple submit button below, which says "Transfer TempData".
On click of that submit button the form will be redirected to a different page (ActionResult submitTempdata), there we will be able to access the @TempData["tempdata"] value.
public ActionResult submitTempdata() { TempData["tempdata"] = string.Format("This tempData string generated at {0}", DateTime.Now); return RedirectToAction("viewbag-tempdata"); }
public TempDataDictionary TempData { get; set; }
You can add key-value pair to TempData, here is an example of how you can write TempData at Controller
TempData["PageTtitle"]="I am learning TempData at WebTrainingRoom";
<h1>@TempData["PageTtitle"]</h1>
You also can add any custom object, list, array in TempData, and cast them back in right data type in View. here is an example.
public ActionResult actionTempata()
{
ArrayList alColors = new ArrayList();
alColors.Add("Red");
alColors.Add("Green");
alColors.Add("Yellow");
alColors.Add("White");
alColors.Add("Orange"); alColors.Add("Blue");
alColors.Add("Black");
TempData["Colors"] = alColors;
return View();
}
Now in View (razor) you can access the TempData property this way.
@{ ArrayList _colors = TempData["Colors"] as ArrayList; foreach (string color in _colors) { <div>@color</div> } }
Ideal use of TempData when you have small amount of dictionary data (with key-value pair) to be transferred from current page to a different page (view).
TempData["student"] = "Anushka"; ViewData["student"] = "Anisha";
then access the TempData @TempData["student"] ,this will print "Anushka" only, not "Anisha", because they use different dictionary
There is no intellisense that will get you the key name you have specified in TempData, So you have to remember the exact name while accessing it, also the type,
for example ArrayList _colors = TempData["Colors"] as ArrayList;
we have converted to ArrayList, so you have to remember both key name and type
You may also learn about ViewBag and Viewdata in Asp.net MVC, or read difference among ViewBag, ViewData and Tempdata