Click here to Skip to main content
11,413,548 members (72,818 online)
Click here to Skip to main content
Technical Blog

What is ViewData, ViewBag and TempData? – MVC options for passing data between current and subsequent request

, 15 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
ASP.NET MVC offers us three options ViewData, VieBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets discuss or get key points on those three objects: Similarities bet


ASP.NET MVC offers us three options ViewData, VieBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets 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 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:

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

In View:

@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 that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. 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 use 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. generally used to store only one time messages like error messages, validation messages.

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}
<pre><pre lang="cs">public ActionResult About()
{
    var model= TempData["ModelName"];
    return View(model);
}
The last mechanism is the Session which work like the ViewData, like a Dictionary that take 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 need 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)

Share

About the Author

Monjurul Habib
Software Developer (Senior)
Bangladesh Bangladesh
A life-long-learner, maker and soft music fan. Likes building things to solve problems. Lives in Dhaka with wife and wonderful, smart kid and works as a Senior Software Engineer in applications architecture team.

He has years of successful records serving mid and large scale .NET applications. Have a wide range of experience working in domestic and international client environment. Expertise in different areas of software development life cycles and Software Architecture.

I am always looking for new information and value your feedback (especially where I got something wrong!).
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
Generalthanks indeed very good article and example Pin
Member 4744977 at 28-Dec-14 3:13
memberMember 474497728-Dec-14 3:13 
General[My vote of 2] TempData explanation misleading Pin
Dominik Raniszewski at 20-Oct-14 18:35
memberDominik Raniszewski20-Oct-14 18:35 
GeneralMy vote of 3 Pin
softskiper at 10-Aug-14 22:05
membersoftskiper10-Aug-14 22:05 
QuestionVote Pin
Member 8096926 at 30-Jul-14 5:51
memberMember 809692630-Jul-14 5:51 
GeneralMy vote of 4 Pin
Manoj B. Kalla at 21-Jul-14 20:15
memberManoj B. Kalla21-Jul-14 20:15 
GeneralMy vote of 3 Pin
Ali Murad at 25-May-14 22:23
memberAli Murad25-May-14 22:23 
GeneralMy vote of 2 Pin
Andrija Juric at 24-Apr-14 0:01
memberAndrija Juric24-Apr-14 0:01 
GeneralMy vote of 5 Pin
Pham Hong Sang at 11-Apr-14 17:02
memberPham Hong Sang11-Apr-14 17:02 
GeneralThanks Pin
Md.Mithun at 20-Feb-14 22:56
memberMd.Mithun20-Feb-14 22:56 
NewsSomeone has copied your code Pin
Subhadeep Mitra at 27-Jan-14 20:33
memberSubhadeep Mitra27-Jan-14 20:33 
QuestionWhy do these exist? Pin
Member 8047489 at 4-Dec-13 4:37
memberMember 80474894-Dec-13 4:37 
QuestionWhat is an HTTP Request? Pin
Colin Angus Mackay at 3-Dec-13 0:19
memberColin Angus Mackay3-Dec-13 0:19 
AnswerRe: What is an HTTP Request? Pin
saineshwar at 9-Apr-14 21:44
membersaineshwar9-Apr-14 21:44 
GeneralUsing Session["myThing"] Pin
Roger Tranchez at 23-Oct-13 3:30
memberRoger Tranchez23-Oct-13 3:30 
Questionthanks, not explained everywhere Pin
Member 10305912 at 29-Sep-13 22:25
memberMember 1030591229-Sep-13 22:25 
Question[My vote of 2] Session is not stored in a cookie Pin
morzel at 20-Sep-13 6:10
membermorzel20-Sep-13 6:10 
QuestionScope of ViewData and ViewBag and TempData Pin
Antariksh Verma at 15-Sep-13 21:54
professionalAntariksh Verma15-Sep-13 21:54 
AnswerRe: Scope of ViewData and ViewBag and TempData Pin
Imran Abdul Ghani at 9-Jul-14 21:26
memberImran Abdul Ghani9-Jul-14 21:26 
GeneralMy vote of 5 Pin
Member 10222501 at 22-Aug-13 0:07
memberMember 1022250122-Aug-13 0:07 
QuestionHi! Pin
Newbie2014 at 20-Aug-13 4:47
memberNewbie201420-Aug-13 4:47 
AnswerRe: Hi! Pin
Monjurul Habib at 20-Aug-13 20:40
professionalMonjurul Habib20-Aug-13 20:40 
GeneralMy vote of 5 Pin
manoj kumar choubey at 7-Aug-13 21:06
membermanoj kumar choubey7-Aug-13 21:06 
GeneralRe: My vote of 5 Pin
Monjurul Habib at 12-Aug-13 12:46
professionalMonjurul Habib12-Aug-13 12:46 
GeneralMy vote of 3 Pin
mayank.gpt1 at 29-Jul-13 3:54
membermayank.gpt129-Jul-13 3:54 
GeneralRe: My vote of 3 Pin
Monjurul Habib at 1-Aug-13 11:09
professionalMonjurul Habib1-Aug-13 11:09 
GeneralCrisp and Clear Pin
mynutshell at 18-Jul-13 21:34
membermynutshell18-Jul-13 21:34 
GeneralRe: Crisp and Clear Pin
Monjurul Habib at 24-Jul-13 9:27
professionalMonjurul Habib24-Jul-13 9:27 
GeneralMy vote of 5 Pin
Antariksh Verma at 15-Jul-13 19:47
professionalAntariksh Verma15-Jul-13 19:47 
GeneralRe: My vote of 5 Pin
Monjurul Habib at 24-Jul-13 9:26
professionalMonjurul Habib24-Jul-13 9:26 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun at 1-Jul-13 23:27
memberHumayun Kabir Mamun1-Jul-13 23:27 
GeneralRe: My vote of 5 Pin
Monjurul Habib at 2-Jul-13 2:13
professionalMonjurul Habib2-Jul-13 2:13 
GeneralMy vote of 5 Pin
Abey Thomas at 13-Jun-13 3:06
memberAbey Thomas13-Jun-13 3:06 
GeneralRe: My vote of 5 Pin
Monjurul Habib at 13-Jun-13 7:03
professionalMonjurul Habib13-Jun-13 7:03 
QuestionOnly C#? Pin
csugden at 23-May-13 8:50
membercsugden23-May-13 8:50 
GeneralMy vote of 2 Pin
Prince Antony G at 23-May-13 1:13
memberPrince Antony G23-May-13 1:13 
GeneralRe: My vote of 2 Pin
Monjurul Habib at 23-May-13 23:00
professionalMonjurul Habib23-May-13 23:00 
GeneralMy vote of 5 Pin
Hasibul Haque at 7-Mar-13 6:24
memberHasibul Haque7-Mar-13 6:24 
GeneralRe: My vote of 5 Pin
Monjurul Habib at 7-Mar-13 7:34
memberMonjurul Habib7-Mar-13 7:34 
Questionhow to redirect from from controller to view Pin
abizer qubbawala at 5-Feb-13 1:45
memberabizer qubbawala5-Feb-13 1:45 
AnswerRe: how to redirect from from controller to view Pin
Monjurul Habib at 7-Mar-13 7:39
memberMonjurul Habib7-Mar-13 7:39 
GeneralMy vote of 5 Pin
namrathamahesh at 23-Jan-13 18:28
membernamrathamahesh23-Jan-13 18:28 
GeneralRe: My vote of 5 Pin
Monjurul Habib at 7-Mar-13 7:34
memberMonjurul Habib7-Mar-13 7:34 
GeneralMy vote of 5 Pin
Mahbub_Hasan_Aiub at 20-Nov-12 7:50
memberMahbub_Hasan_Aiub20-Nov-12 7:50 
GeneralRe: My vote of 5 Pin
Monjurul Habib at 20-Nov-12 7:52
memberMonjurul Habib20-Nov-12 7:52 
QuestionCould you help with my MVC edit, delete function? Pin
xnaLearner at 19-Oct-12 9:52
memberxnaLearner19-Oct-12 9:52 
AnswerRe: Could you help with my MVC edit, delete function? Pin
Monjurul Habib at 3-Nov-12 1:14
memberMonjurul Habib3-Nov-12 1:14 
GeneralMy vote of 5 Pin
cisjackie at 15-Oct-12 21:29
membercisjackie15-Oct-12 21:29 
GeneralRe: My vote of 5 Pin
Monjurul Habib at 15-Oct-12 21:34
memberMonjurul Habib15-Oct-12 21:34 
GeneralMy 5 Pin
Shahriar Iqbal Chowdhury at 15-Oct-12 11:54
memberShahriar Iqbal Chowdhury15-Oct-12 11:54 
GeneralRe: My 5 Pin
Monjurul Habib at 15-Oct-12 11:56
memberMonjurul Habib15-Oct-12 11:56 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150427.1 | Last Updated 15 Oct 2012
Article Copyright 2012 by Monjurul Habib
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid