Click here to Skip to main content
15,860,943 members
Articles / Web Development / ASP.NET / ASP.NET4.0

What is ViewData, ViewBag and TempData? – MVC Options for Passing Data Between Current and Subsequent Request

Rate me:
Please Sign up or sign in to vote.
4.76/5 (148 votes)
15 Oct 2012CPOL2 min read 1.1M   110   60
What is ViewData, ViewBag and TempData?

ASP.NET MVC offers us three options - ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Let's discuss or get key points on those three objects:

Similarities between ViewBag & ViewData:

  1. Helps to maintain data when you move from controller to view.
  2. Used to pass data from controller to corresponding view.
  3. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  1. ViewData is a dictionary of objects that is derived from ViewDataDictionary class and is accessible using strings as keys.
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  3. ViewData requires typecasting for complex data type and check for null values to avoid error.
  4. ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

C#
public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}
C#
public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
} 

In View:

C#
@ViewBag.Name 
@ViewData["Name"] 

TempData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is the life cycle of the object. TempData keeps the information for the time of an HTTP Request. This mean only from one page to another. This also works with a 302/303 redirection because it’s in the same HTTP Request. It helps to maintain data when you move from one controller to other controller or from one action to other action. In other words, when you redirect, “Tempdata” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is used when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. It is generally used to store only one time messages like error messages, validation messages.

C#
public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}
C#
public ActionResult About() 
{     
    var model= TempData["ModelName"];     
    return View(model); 
} 

The last mechanism is the Session which works like the ViewData, like a Dictionary that takes a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also needs more verification to never have any confidential information. Regarding ViewData or ViewBag, you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular ASP.NET MVC request. You can use ViewData/ViewBag in your child action, but be careful that you are not using it to populate the unrelated data which can pollute your controller.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Singapore Singapore
A life-long-learner, maker and soft music fan. Likes building things to solve problems. Years of successful records serving mid and large scale .NET applications in domestic and international client environment. Expertise in different areas of software development life cycles and Software Architecture.

Always looks for new technology and loves to get hands dirty Smile | :)

Comments and Discussions

 
GeneralUsing Session["myThing"] Pin
Roger Tranchez23-Oct-13 2:30
Roger Tranchez23-Oct-13 2:30 
Questionthanks, not explained everywhere Pin
Member 1030591229-Sep-13 21:25
Member 1030591229-Sep-13 21:25 
Question[My vote of 2] Session is not stored in a cookie Pin
morzel20-Sep-13 5:10
morzel20-Sep-13 5:10 
QuestionScope of ViewData and ViewBag and TempData Pin
Antariksh Verma15-Sep-13 20:54
professionalAntariksh Verma15-Sep-13 20:54 
AnswerRe: Scope of ViewData and ViewBag and TempData Pin
Imran Abdul Ghani9-Jul-14 20:26
Imran Abdul Ghani9-Jul-14 20:26 
GeneralMy vote of 5 Pin
Member 1022250121-Aug-13 23:07
Member 1022250121-Aug-13 23:07 
QuestionHi! Pin
Newbie201420-Aug-13 3:47
Newbie201420-Aug-13 3:47 
AnswerRe: Hi! Pin
Monjurul Habib20-Aug-13 19:40
professionalMonjurul Habib20-Aug-13 19:40 
Will try . Thanks.
Life gives hundred reasons to cry, but thousand reasons to smile. So, keep smiling Smile | :)

GeneralMy vote of 5 Pin
Manoj Kumar Choubey7-Aug-13 20:06
professionalManoj Kumar Choubey7-Aug-13 20:06 
GeneralRe: My vote of 5 Pin
Monjurul Habib12-Aug-13 11:46
professionalMonjurul Habib12-Aug-13 11:46 
GeneralMy vote of 3 Pin
Mayank.Gupta29-Jul-13 2:54
Mayank.Gupta29-Jul-13 2:54 
GeneralRe: My vote of 3 Pin
Monjurul Habib1-Aug-13 10:09
professionalMonjurul Habib1-Aug-13 10:09 
GeneralCrisp and Clear Pin
mynutshell18-Jul-13 20:34
mynutshell18-Jul-13 20:34 
GeneralRe: Crisp and Clear Pin
Monjurul Habib24-Jul-13 8:27
professionalMonjurul Habib24-Jul-13 8:27 
GeneralMy vote of 5 Pin
Antariksh Verma15-Jul-13 18:47
professionalAntariksh Verma15-Jul-13 18:47 
GeneralRe: My vote of 5 Pin
Monjurul Habib24-Jul-13 8:26
professionalMonjurul Habib24-Jul-13 8:26 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun1-Jul-13 22:27
Humayun Kabir Mamun1-Jul-13 22:27 
GeneralRe: My vote of 5 Pin
Monjurul Habib2-Jul-13 1:13
professionalMonjurul Habib2-Jul-13 1:13 
GeneralMy vote of 5 Pin
Abey Thomas13-Jun-13 2:06
Abey Thomas13-Jun-13 2:06 
GeneralRe: My vote of 5 Pin
Monjurul Habib13-Jun-13 6:03
professionalMonjurul Habib13-Jun-13 6:03 
QuestionOnly C#? Pin
csugden23-May-13 7:50
professionalcsugden23-May-13 7:50 
GeneralMy vote of 2 Pin
Prince Antony G23-May-13 0:13
Prince Antony G23-May-13 0:13 
GeneralRe: My vote of 2 Pin
Monjurul Habib23-May-13 22:00
professionalMonjurul Habib23-May-13 22:00 
GeneralMy vote of 5 Pin
Hasibul Haque7-Mar-13 5:24
professionalHasibul Haque7-Mar-13 5:24 
GeneralRe: My vote of 5 Pin
Monjurul Habib7-Mar-13 6:34
professionalMonjurul Habib7-Mar-13 6:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.