As many technical protals, blogs and tutorials have a huge definition of ViewData, ViewBag and TempData, I’m not going to peep around again with definitions.Let us explore something out of the box about these concepts.

If we want to send extra data from controller to view then use these else go for Model Binding and Strongly typed Views.

This is so because to be precise ViewBag doesn’t support compile time error checking.

Eg: Misspell of  key in ViewBag or presence of null values or access between different types.

  1. TempData and ViewData requires typecasting and check for null values whereas ViewBag doesn’t require it.
  2. Since ViewBag doesn’t require typecasting it has a great potential for run time errors so avoid using ViewBag for important data transfer.
  3. 1)First of all remember that we can send data from controller to view via ViewBag and ViewData and ofcourse by TempData too.
  4. 2)But TempData has additional feature to send data from one Controller action method to another action method.
  5. 3)After setting value in ViewBag, ViewData and TempData ,if a redirection happens then the value in the both becomes null, but TempData value persists.
  6. 4)TempData value remains as long as the continuous redirections happen.
  7. 5)TempData value will be lost once it is read or if the user’s session times out or a refresh of the page happens.

To illustrate these concepts lets look at the below code.

public class HomeController : Controller
{
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");
/*instead if we return View then in View ViewBag,ViewData and TempData values will be available.Even a refresh of the page causes the controller and action method to be again invoked which will cause the same result without the values of ViewData,ViewBag and TempData being emptied*/
}


public ActionResult Show()
{
var testdata= ViewData["FeaturedProduct"];
//As redirection happend ViewData, ViewBag values are lost
var testbag = ViewBag.product;
var tempda = TempData["FeaturedProduct"];
//TempData retains its value
return Redirect("~/Home/blow");
/*return View(); causes tempdata to be null since we read a TempData value in the Show view or a refresh will also make TempData value lost*/
}
public ActionResult blow()
{
var tempda = TempData["FeaturedProduct"];
//TempData still remains even after two redirections.
return View("Show");
}
}

Here is the Show view code below

@{
var tevar = TempData["FeaturedProduct"] as Product;
}
@{
if (TempData["FeaturedProduct"]!=null)
{@tevar.Name
}
else{
Sorry tempdata values perished
}
}

This is all about TempData. Hope You mastered the TempData concept.

Advertisements