TempData in ASP.NET MVC in C#

In this article raviteja swayampu explained about how to use TempData in ASP.NET MVC with small example.TempData is a dictionary object to store data temporarily. It is a TempDataDictionary class type and instance property of the Controller base class.

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary. It  stays for a subsequent HTTP Request(means it can keep live data between two consecutive HTTP requests both request and redirect) as opposed to other options (ViewBag and ViewData) those stay only for current request. So, TempData can be used to maintain data between controller actions as well as redirects.
It will also help to pass state between action methods also and it uses session variable to store data.It is generally used to store one time messages like error messages and validation messages.

Note:  Just like ViewData, typecasting and null checks required for TempData also in order to avoid errors run time errors while rendering cshtml pages and in other action methods.

Lets see how to use tempdata in a practical scenario from one controller to another.
public ActionResult FirstRequest()
{
    List TempDataTest = new List();
    TempDataTest.Add("Raviteja");
    TempDataTest.Add("Krishna");
    TempDataTest.Add("Sridhar");
    TempData["CustomerName"] = TempDataTest;
    return View();
}

public ActionResult ConsecutiveRequest()
{
    List modelData = TempData["CustomerName"] as List;
    TempData.Keep();
    return View(modelData);
}

In View we will display TempData as below.
@{
  if(TempData["CustomerName"]!=null){
 List<string> list=TempData["CustomerName"] as List<string>
 foreach(var item in list){
  //Writing temp data list in html page
  <h3>@item</h3>
 }
  }
}

Generally we do not think about where tempdata is stored.Obviously, it does not matter for developer to think about where it is stored.I hope this information is good about tempdata to know more like base classes of Dictionary class and methods visit MSDN.


TempData in ASP.NET MVC in C# TempData in ASP.NET MVC  in C# Reviewed by raviteja swayampu on 22:55:00 Rating: 5

No comments: