0

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.

Intriguing
  • 125
  • 3
  • 13
  • Why do you expect that `TempData` will be null in the Show view? It will be null if you reload the Show action or redirect away from it. – Darin Dimitrov Feb 19 '17 at 05:39
  • @DarinDimitrov So If it was not null then why TempData value is not getting assigned to tevar variable in View? – Intriguing Feb 19 '17 at 05:51

2 Answers2

1

You've got a typo in your Show view:

@{
var tevar = TempData["Featured Product"] as Product;
}

should of course be:

@{
var tevar = TempData["FeaturedProduct"] as Product;
}

Make sure that you access the value using the same key as you stored it with.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

I could now clearly comprehend the difference between ViewBag, ViewData, TempData. ViewBag and ViewData value will be lost after redirection, but TempData value will remain between the redirection until a refresh of the current action method occurs or if we navigate to other action method.

Intriguing
  • 125
  • 3
  • 13