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