Basically I am learning about difference between ViewBag, ViewData, TempData in practical.I am in confusion with the theory of these concepts so I want to see how things happen in practical.
I learned that TempData is used to send data from controller to controller i.e from one action method to another action method, and it is short lived.Even then I can pass TempData value to a View as well. As I read that it's value gets null after subsequent request. But In my sample code snippet though there exist a value in TempData after a redirection, I'm unable to assign it to a variable.
public ActionResult Index()
{
var featuredProduct = new Product
{
Name = "Special cupcakes",
Des = "Delectable vanilla and chocolate cupcakes",
Creationdate= DateTime.Now,
Expirydate= DateTime.Today.AddDays(7)
};
ViewData["FeaturedProduct"] = featuredProduct;
ViewBag.product = featuredProduct;
TempData["FeaturedProduct"] = featuredProduct;
return Redirect("~/Home/Show");
}
As this is the first redirection i.e next subsequent request after setting TempData, the value should persist in TempData of Show Action method.
public ActionResult Show()
{
var testdata= ViewData["FeaturedProduct"];
var testbag = ViewBag.product;
var tempdata = TempData["FeaturedProduct"];
return View();
}
Now my confusion is around here. If I want to access TempData in the Show View, I expect that it should be null. When I see in Quick Watch,it's value persisted and it's value is not getting assigned to the variable.So What exactly is happening with TempData.
@{
var tevar = TempData["Featured Product"] as Product;
}
@{
if (TempData["Featured Product"]!=null)
{
<b><u>
@tevar.Name
</u></b>
}
else{
<b> Sorry tempdata values perished</b>
}
}
Though this appear very basic please bear with me and explain me what happening with TempData in my code. Thank You.