Whats Difference in performance of ViewBag and View Data and when to use which one

2.4k views Asked by At

I am new to MVC. I want to know that when I should use ViewData, ViewBag and TempData to pass objects and is there any difference in performance of ViewData and ViewBag?

2

There are 2 answers

0
Farrukh Liaqat On BEST ANSWER

View Data: View Data is a dictionary object that is derived from View Data Dictionary class. View Data is a property of Controller Base class. View Data is used to pass data from controller to corresponding view. Usage:

public ActionResult Index()

{

    ViewData.Name = "Tony Boss";
    return View();

}

View Bag View Bag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. Basically it is a wrapper around the View Data and also used to pass data from controller to corresponding view. View Bag is a property of Controller Base class.

Usage:

public ActionResult Index()

{

    ViewBag.Name = "Tony Boss";
    return View();

}

Temp Data: Temp Data is a dictionary object that is derived from Temp Data Dictionary class and stored in short lives session Temp Data is a property of Controller Base class. Temp Data is used to pass data from current request to subsequent request (means redirecting from one page to another).

0
Somdev Singh On

ViewData

ViewData is used to pass data from controller to view
It is derived from ViewDataDictionary class
It is available for the current request only
Requires typecasting for complex data type and checks for null values to avoid error
If redirection occurs, then its value becomes null

ViewBag

ViewBag is also used to pass data from the controller to the respective view
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
It is also available for the current request only
If redirection occurs, then its value becomes null
Doesn’t require typecasting for complex data type

TempData

TempData is derived from TempDataDictionary class
TempData is used to pass data from the current request to the next request
It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages 

Refer below link for the performance check

http://spiritofdev.blogspot.in/2011/12/performance-of-c-40-dynamic-vs.html