difference between viewbag,viewdata and tempdata in asp.net mvc

Introduction :

In this article I will explain with an example, Differences of ViewData, ViewBag and TempData in ASP.Net MVC. ViewData, ViewBag and TempData are used for transferring data and objects between Controller to View or from one Controller to another Controller in ASP.Net MVC.

ViewBage :

  • ViewBag is a type object
  • ViewBag is a dynamic property and it makes use of the C# 4.0 dynamic features
  • ViewBag is used for passing value from Controller to View
  • No need for type casting
  • ViewBag is available for Current Request only. when redirection occures data will be destroyed.
  • ViewBag is slower than ViewData

Example:

public class codelernerController : Controller
{

public ActionResult Index()
{
ViewBag.Message = “viewbag example in mvc”;
return View();
}
}

View :

<h2>@ViewBag.Message </h2>

ViewData :

  • ViewData is derived from the ViewDataDictionary class, data is stored in key,value pairs.
  • Data is stored as Object in ViewData.
  • While retrieving the data it needs type casting and NULL checks.
  • ViewData is used for passing value from Controller to View.
  • ViewBag is available for Current Request only, when redirection occures data will be destroyed.

public class codelernerController : Controller
{

public ActionResult Index()
{
ViewData[“Message“]. = “viewData example in mvc”;
return View();
}
}

View :

<h2>@ViewData[“Message“] </h2>

TempData :

  • TempDatais derived from the TempDataDictionary class, data is stored in key,value pairs.
  • Data is stored as Object in ViewData.
  • While retrieving the data it needs type casting and NULL checks.
  • TempData is used for passing value from Controller to View and controller to controller.
  • TempData is available for Current Request and Subsequent Requests.It will not be destroyed on redirection.

public class codelernerController : Controller
{

public ActionResult Index()
{
TempData[“Message“]. = “TempData example in mvc”;
return View();
}
}

<h2>@TempData[“Message“] </h2>

Conclusion :

ViewData, ViewBag and TeampData are used for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and it helps us to transfer the data from controller to view where as TempData also works during the current and subsequent requests.

 

SEE MORE

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *