September 4, 2013

ViewBag vs ViewData vs TempData Objects In Asp.Net MVC

In MVC, we have three types of objects - ViewBag, ViewData and TempData, use to pass data from controller to view and controller to controller. Each object has its own functionality, importance and area in which it use. Here I show these areas, where you can use one of them as requirement. 

1. ViewBag
    =======

  • ViewBag is a wrapper around ViewData which is use to pass data from Controller to View. This object is the feature of .Net 4.0.
  • ViewBag is a dynamic property which is don't require any type of typecasting for complex data types.
  • ViewBag's value become null if redirection occur because its life lies only during current request.

2. ViewData
    =======

  • ViewData is a dictionary object that is derived from ViewDataDictionary class which is used to pass data from controller to corresponding view.
  • ViewData requires typecasting for complex data type. It is recommended to check for null values to avoid error.
  • ViewData's value become null if redirection occur because its life lies only during current request.

3. TempData
    =======

  • TempData is a dictionary object that is derived from TempDataDictionary class which is used to pass data from current request to subsequent request in case of redirection.
  • TempData having the short lives session and lies only till the target view is fully loaded.
  • It requires type casting for complex data type. It is recommended to check for null values to avoid error. 

* ViewData, ViewBag and TempData Current Request Example
============================================

public class HomeController : Controller
{
  public ActionResult Index()
  {
     var subscriber = new Subscribers
     {
  Id = 1,
FirstName = "John",
        LastName = "Smith",
  IsActive = true
     }; 

     ViewData["Subscriber"] = subscriber;
     ViewBag.Subscriber = subscriber;
     TempData["Subscriber"] = subscriber; 
    
     return View(); 
  }
}

@model SubscriberViewModel

@{
    ViewBag.Title = "Welcome to Home Page";

    // Need Typcasting
    var viewDataSubscriber = 
        ViewData["Subscriber"] as Subscriber; 
    var tempDataSubscriber = 
        TempData["Subscriber"] as Subscriber;
}

<h2>@ViewBag.Title</h2>

 Subscriber Profile:
 <h4>@ViewBag.Subscriber.SubscriberName</h4>
 <h3>@viewDataSubscriber.SubscriberName</h3>
 <h2>@tempDataSubscriber.SubscriberName</h2>
</div> 

* ViewData, ViewBag and TempData Next Request Example
==========================================

public class HomeController : Controller
{
  public ActionResult Index()
  {
     var subscriber = new Subscribers
     {
  Id = 1,
FirstName = "John",
        LastName = "Smith",
  IsActive = true
     }; 

     ViewData["Subscriber"] = subscriber;
     ViewBag.Subscriber = subscriber;
     TempData["Subscriber"] = subscriber;
    
     // After the redirection, ViewData and ViewBag objects will be null 
     // Only TempData will exist after redirection 
     return RedirectToAction("Create", "Subscriber");
  }

@model CreateSubscriberViewModel

@{ 
   ViewBag.Title = "Create Subscriber";

   // Need Typcasting
   var tempDataSubscriber = 
       TempData["Subscriber"] as Subscriber; 
}

* TempData with Keep method
   ====================

To hold the value in TempData after completion of request, there is an method named "Keep()" present. Call this method in current action method which keep you values in TempData. There are two types overload methods to retains value after current request completion.

1. void Keep()
    =========

If you call this method in current action, It ensures that all the items in TempData are not removed at the end of the current request. 

@model CreateSubscriberViewModel

@{ 
   ViewBag.Title = "Create Subscriber";

   // Need Typcasting
   var tempDataSubscriber = TempData["Subscriber"] as Subscriber;

   // Retains all strings values 
   TempData.Keep();
}

2. void Keep(string key)
=================

If you call this method in current action, It ensures the specific item in TempData are not removed at the end of the current request. 

@model CreateSubscriberViewModel

@{ 
   ViewBag.Title = "Create Subscriber";

   // Need Typcasting
   var tempDataSubscriber = TempData["Subscriber"] as Subscriber;

   // Retains all strings values 
   TempData.Keep("Subscriber");
}

* Summary
=========

Hope you now able to understand that which object is use where. If you have any query remains then let me know. Stay Tune:)