I saw the ViewBag
in MVC 3. How's that different than ViewData
in MVC 2?

- 1,669
- 3
- 27
- 50

- 48,855
- 59
- 128
- 165
17 Answers
It uses the C# 4.0 dynamic feature. It achieves the same goal as viewdata and should be avoided in favor of using strongly typed view models (the same way as viewdata should be avoided).
So basically it replaces magic strings:
ViewData["Foo"]
with magic properties:
ViewBag.Foo
for which you have no compile time safety.
I continue to blame Microsoft for ever introducing this concept in MVC.
The name of the properties are case sensitive.

- 3,585
- 1
- 24
- 26

- 1,023,142
- 271
- 3,287
- 2,928
-
12For what purpose you are blaming microsoft? If no viewdata how could we bind dropdownlist from model. (I don't think using selectlist inside model would be a good idea) – Subin Jacob Nov 13 '13 at 10:46
-
15@SubinJacob You should really make a new question if you want an answer to this. Creating a SelectList is definitely the way to go to make a dropdownlist. – MiniRagnarok Nov 26 '13 at 15:10
-
@SubinJacob, I assume he is blaming MS for introducing the dynamic features. – MEMark Mar 29 '14 at 21:41
-
Why Microsoft added such features?. PHP. Don't forget that PHP is practically the de-facto language for program public websites. – magallanes Aug 10 '14 at 21:56
-
I think he's trying to say the "correct" way of doing it would be by using ViewModels always. Introduction of ViewData/ViewBag let people do it a non-MVC way. Perhaps to let the old WebForms folks have thier Session data? – vidalsasoon Aug 28 '14 at 13:12
-
29I think that's a little subjective. Strongly typed models are nice and yada yada, but for the scenarios where you're quickly getting a view up and running, ViewBag and alike do the job quicker than Controller, View, Model, AutoMapper to ViewModel, etc. – Craig Brett Sep 12 '14 at 10:15
-
13@Darin, why do you "blame" Microsoft for introducing this? It just a tool given to developers. If you know what you are doing, you can make the most out of it. If you don't like it or feel like its more prone to errors, simply don't use it. :) – Bilal Fazlani Mar 15 '15 at 09:19
-
I would upvote you a million times if I could for blaming Microsoft! ;) – ZolaKt Apr 17 '15 at 11:32
-
3In each of my .cshtml views, I use ViewBag to set things in the layout, like body class. For example, say I have an account page, Account.cshtml. At the top, I set ViewBag.BodyClass = "page-account", so that the layout generates – jbyrd Oct 15 '15 at 17:28
-
6How you suggest to pass data between partials and layout? People blame when they don't see the full picture. I imagine you have basecontrollers and base view models or static/singletons objects everywhere. Guess what, better learn to use view data and blame yourself for using the wrong tool for the job. – Bart Calixto Feb 12 '16 at 17:18
-
@magallanes The `dynamic` type causes C# to (finally) have support for late-bound `IDispatch` COM objects. When you don't have, or cannot get, a type library imported into your language, you can still use late-binding if the COM object supports the `IDispatch` interface. Other strongly and statically typed languages had support automatic marshalling of parameters, without having to build up the complicated set of structures you would have to pass to `IDispatch.Invoke`. – Ian Boyd May 14 '16 at 16:11
-
**View Bag** - It is a dynamic wrapper around view data. When you use Viewbag type, casting is not required. It uses the dynamic keyword internally. – Raju Padhara Jun 02 '16 at 10:25
-
2"for which you have no compile time safety." It's only intellisense in Razor views. The project will still compile if you have `model.unknown`. Your project will then blow at runtime. At least with `ViewBag.unknown` your view will not blow. – Norbert Norbertson Dec 15 '16 at 13:59
-
Im a little confused, Is ViewData bad or ViewBag bad? or are they both bad and you should use ViewModels. My personal view is that ViewModels should be used in all cases but I admit i dont practice what i preach due to consistency reasons but there is some validity to use ViewBags in certain circumstances but used sparingly. – Frazer Apr 28 '17 at 07:45
-
@Frazer They're both "bad" in the sense that the clean way would be using ViewModels. However, as stated in other comments, they're both handy tools for starters or for quickly getting your page up and running. – Stacky Nov 24 '21 at 14:11
Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.
Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel as noted in this snippet from MVC 3 release notes:
(edited 10-8-12) It was suggested I post the source of this info I posted, here is the source: http://www.asp.net/whitepapers/mvc3-release-notes#_Toc2_4
MVC 2 controllers support a ViewData property that enables you to pass data to a view template using a late-bound dictionary API. In MVC 3, you can also use somewhat simpler syntax with the ViewBag property to accomplish the same purpose. For example, instead of writing ViewData["Message"]="text", you can write ViewBag.Message="text". You do not need to define any strongly-typed classes to use the ViewBag property. Because it is a dynamic property, you can instead just get or set properties and it will resolve them dynamically at run time. Internally, ViewBag properties are stored as name/value pairs in the ViewData dictionary. (Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel property.)

- 4,141
- 3
- 29
- 48
-
The question asks the difference between `ViewData` and `ViewBag`, not about `ViewModel`. – Matthew Flaschen Nov 07 '11 at 22:46
-
Thanks for the heads-up Matthew Flaschen, I had a typo in the response and fixed it, now reads "ViewData" instead of ViewModel which was a mistake. :) – Rich Bianco Nov 20 '11 at 20:02
-
Now it's incorrect. Neither was renamed to the other. They both still exist. One is `dynamic` and supports `ViewBag.Message`. One uses the old `ViewData["Message"]` syntax. – Matthew Flaschen Nov 20 '11 at 21:32
-
Matthew, You are correct. I've revised this so that it is correct. It isn't necessarily the best answer but at least it is now accurate. When I originally posted I wrongly *thought* the question was about ViewModel – Rich Bianco Nov 22 '11 at 07:10
-
1+1 But, what source are you quoting from...? Should really provide a link. – Sam May 18 '12 at 14:31
-
1Thank you Sam for the suggestion. I have added a link to the original source. – Rich Bianco Oct 08 '12 at 20:42
ViewBag vs ViewData in MVC
http://royalarun.blogspot.in/2013/08/viewbag-viewdata-tempdata-and-view.html
Similarities between ViewBag & ViewData :
Helps to maintain data when you move from controller to view. Used to pass data from controller to corresponding view. 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:
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error. ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:
public ActionResult Index()
{
ViewBag.Name = "Arun Prakash";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Arun Prakash";
return View();
}
Calling in View
@ViewBag.Name
@ViewData["Name"]

- 1,564
- 4
- 26
- 36

- 880
- 10
- 10
-
10your answer indicate `typecasting` but you did not show how typecasting is performed – user786 Jun 14 '16 at 20:04
ViewData
: It requires type casting for complex data types and checks for null values to avoid errors.
ViewBag
: It doesn’t require type casting for complex data types.
Consider the following example:
public class HomeController : Controller
{
public ActionResult Index()
{
var emp = new Employee
{
EmpID=101,
Name = "Deepak",
Salary = 35000,
Address = "Delhi"
};
ViewData["emp"] = emp;
ViewBag.Employee = emp;
return View();
}
}
And the code for View
is as follows:
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Welcome to Home Page";
var viewDataEmployee = ViewData["emp"] as Employee; //need type casting
}
<h2>Welcome to Home Page</h2>
This Year Best Employee is!
<h4>@ViewBag.Employee.Name</h4>
<h3>@viewDataEmployee.Name</h3>

- 7
- 2

- 1,600
- 13
- 28
-
6help me to undestand but i think there is a mistake. this `
@ViewBag.emp.Name
` should change to `@ViewBag.Employee.Name
` – Benny Margalit Jan 27 '17 at 09:23
All answers suggest that ViewBag
and/or ViewData
is to pass data from Controller
to Views
which is misinformation. both are very useful to pass data from Views to Layout or Partial to Views (or ViewComponents, etc) It's not controller exclusive.
as the default asp.net sample have this in the layout page:
<title>@ViewData["Title"] - MyApp</title>
and in any view
ViewData["Title"] = "Details";
So then, to asking the question: "what's the difference between ViewBag
and ViewData
?"
The most notable difference is ViewData
is a Strongly Typed Dictionary while
ViewBag
is a dynamic type.
Note that the data inside IS THE SAME
ViewData["Title"] = "MyTitle";
ViewBag.Title; // returns "MyTitle";
When to use one or another?
ViewBag
doesn't support not valid C# names. you can't accessViewData["Key With Space"]
withViewBag
ViewBag.Something
is dynamic and you may have problems when calling methods (like extension methods) that needs to know the exact parameter at compile time.ViewBag
can check for nulls syntactical cleaner:ViewBag.Person?.Name
ViewData
have all the properties of a Dictionary likeContainsKey
,Add
, etc. so you can useViewData.Add("somekey", "somevalue")
keep in mind it might throw exceptions.- Using
ViewData
on views needs TypeCasting whileViewBag
don't.
Knowing the subtle differences, using one or another is much more a taste preference.
Normally you can think of ViewBag.AnyKey
to an alias of ViewData["AnyKey"]

- 19,210
- 11
- 78
- 114
Can I recommend to you to not use either?
If you want to "send" data to your screen, send a strongly typed object (A.K.A. ViewModel) because it's easier to test.
If you bind to some sort of "Model" and have random "viewbag" or "viewdata" items then it makes automated testing very difficult.
If you are using these consider how you might be able to restructure and just use ViewModels.

- 851
- 1
- 12
- 16
-
4Ignoring the "compiler is the first unit test" principal how does a statically typed view model make your code more testable than a dynamic type? Whilst the requirement for tests is more important in a dynamically typed solution, if both solutions implement the same number and type of tests you lose nothing. – Darren Lewis Dec 22 '11 at 11:29
-
I agree, it's a little vague. Perhaps intellisense is involved. – Joshua Ramirez Mar 15 '13 at 07:00
-
1One example would be mocking. If you want to unit test a controller action, it's easier to create a "mock" object to pass around and assert against rather than trying to assert that some string was added to some dictionary or some dynamic field is set to some value - it is a similar concept to service contracts having one "Request" and one "Response" object, rather than taking multiple parameters. – nootn Mar 25 '13 at 12:08
-
how would you pass data from View to Layout if not using either? -1 – Bart Calixto Jul 14 '16 at 19:20
-
There are some subtle differences that mean you can use ViewData and ViewBag in slightly different ways from the view. One advantage is outlined in this post http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx and shows that casting can be avoided in the example by using the ViewBag instead of ViewData.

- 1,872
- 20
- 36
Below is the point to point difference about ViewData, ViewBag, TempData & Session. Credit/copied askforprogram.in , Follow the link for code example that i haven't mentioned here.
ViewData in MVC
- ViewData is property of ControllerBase class.
- ViewData is a type of dictionary object.
- ViewData is key-value dictionary collection.
- ViewData was introduced in MVC 1.0 version.
- ViewData works with .Net framework 3.5 and above.
- Need to do type conversion of code while enumerating.
- ViewData object keeps data only for current request.
ViewBag in MVC
- ViewBag is property of ControllerBase class.
- ViewBag is a type of dynamic object.
- ViewBag is a type of object.
- ViewBag was introduced in MVC 3.0 version.
- ViewBag works with .Net framework 4.0 and above.
- ViewBag uses property and handles it, so no need to do type conversion while enumerating.
- ViewBag object keeps data only for current request.
TempData in MVC
- TempData is property of ControllerBase class.
- TempData is a type of dictionary object.
- TempData is key-value dictionary collection.
- TempData was introduced in MVC 1.0 version.
- TempData works with .Net framework 3.5 and above.
- Need to do type conversion of code while enumerating.
- TempData object is used to data between current request and subsequent request.
Session in MVC
- Session is property of Controller(Abstract Class).
- Session is a type of HttpSessionStateBase.
- Session is key-value dictionary collection.
- Session was introduced in MVC 1.0 version.
- TempData works with .Net framework 1.0 and above.
- Need to do type conversion of code while enumerating.
- Session object keeps data for all requests. Valid for all requests, never expires.

- 81
- 1
- 2
viewdata: is a dictionary used to store data between View and controller , u need to cast the view data object to its corresponding model in the view to be able to retrieve data from it ...
ViewBag: is a dynamic property similar in its working to the view data, However it is better cuz it doesn't need to be casted to its corressponding model before using it in the view ...

- 1,028
- 1
- 14
- 20
Although you might not have a technical advantage to choosing one format over the other, you should be aware of some important differences between the two syntaxes. One obvious difference is that ViewBag works only when the key you’re accessing is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile. Another key issue to consider is that you cannot pass in dynamic values as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order to choose the correct extension method. If any parameter is dynamic, compilation will fail. For example, this code will always fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the va

- 903
- 11
- 17
public ActionResult Index()
{
ViewBag.Name = "Monjurul Habib";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Monjurul Habib";
return View();
}
In View:
@ViewBag.Name
@ViewData["Name"]

- 329
- 4
- 22
In this way we can make it use the values to the pass the information between the controller to other page with TEMP DATA

- 9
- 1
One main difference I noticed between ViewData and ViewBag is:
ViewData : it will return object does not matter what you have assigned into this and need to typecast again back to the original type.
ViewBag : it is enough smart to return exact type what you have assigned to it it does not matter weather you have assigned simple type (i.e. int, string etc.) or complex type.
Ex: Controller code.
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
Products p1 = new Products();
p1.productId = 101;
p1.productName = "Phone";
Products p2 = new Products();
p2.productId = 102;
p2.productName = "laptop";
List<Products> products = new List<Products>();
products.Add(p1);
products.Add(p2);
ViewBag.Countries = products;
return View();
}
}
public class Products
{
public int productId { get; set; }
public string productName { get; set; }
}
}
View Code.
<ul>
@foreach (WebApplication1.Controllers.Products item in ViewBag.Countries)
{
<li>@item.productId @item.productName</li>
}
</ul>
OutPut Screen.

- 27,717
- 28
- 128
- 190

- 1,635
- 17
- 17
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 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

- 11
- 6
Here ViewData and ViewBag both are used pass data from Controller to View.
1. ViewData
-- ViewData is dictionary object that is derived from ViewDataDictonary class.
-- Data only allow for one request, ViewData values get cleared when page redirecting occurs.
-- ViewData value must be typed cate before use.
Example: In Controller
public ActionResult PassingDatatoViewWithViewData()
{
ViewData["Message"] = "This message shown in view with the ViewData";
return View();
}
In View
@ViewData["Message"];
-- With ViewData is a pair like Key and Value, Message is Key and in inverted comma value is Value.
-- Data is simple so we can not use typecasting here if data is complex then using type casting.
public ActionResult PassingDatatoViewWithViewData()
{
var type= new List<string>
{
"MVC",
"MVP",
"MVVC"
};
ViewData["types"] = type;
return View();
}
-- In View data can be extracted as
<ul>
@foreach (var items in (List<string>)ViewData["types"])
{
<li>@items</li>
}
</ul>
2. ViewBag
--ViewBag uses the dynamic feature.ViewBag wrapper around the ViewData.
-- In ViewBag type casting is required.
-- Same as ViewData, if redirection occurs value becomes null.
Example:
public ActionResult PassingDatatoViewWithViewBag()
{
ViewData.Message = "This message shown in view with the ViewBag";
return View();
}
In View
@ViewBag.vbMessage
--For Complex type use ViewBag
public ActionResult PassingDatatoViewWithViewBag()
{
var type= new List<string>
{
"MVC",
"MVP",
"MVVC"
};
ViewBag.types = type;
return View();
}
-- In View data can be extracted as
<ul>
@foreach (var items in ViewBag.types)
{
<li>@items</li>
}
</ul>
-- the main difference is that ViewBag not required typecasting but ViewData is required typecasting.

- 1,070
- 1
- 15
- 23
ViewBag and ViewData are two means which are used to pass information from controller to view in ASP.Net MVC. The goal of using both mechanism is to provide the communicaton between controller and View. Both have short life that is the value of both becomes null once the redirection has occured ie, once the page has redirected from the source page (where we set the value of ViewBag or ViewData) to the target page , both ViewBag as well as ViewData becomes null.
Despite having these similarities both (ViewBag and ViewData) are two different things if we talk about the implementation of both. The differences are as follows :
1.) If we analyse both implementation wise then we will find that ViewData is a dictionary data structure - Dictionary of Objects derived from ViewDataDictionary and accessible using strings as Keys to these values while ViewBag makes use of the dynamic features introduced in C#4.0 and is a dynamic property.
2.) While accessing the values form ViewData , we need to typecast the values (datatypes) as they are stored as Objects in the ViewData dictionary but there is no such need if we are accessing th value in case of ViewBag.
3.) In ViewBag we can set the value like this :
ViewBag.Name = "Value";
and can access as follows:
@ViewBag.Name
While in case of ViewData the values can be set and accessed as follows: Setting ViewData as follows :
ViewData["Name"] = "Value";
and accessing value like this
@ViewData["Name"]
For more details click here:

- 3,132
- 2
- 20
- 28
-
2sorry I downvoted but this answer takes several paragraphs to say nothing useful. The useful thing missing from the accepted answer would be the sentence "viewbag is a dynamic wrapper around viewdata" which I learned from http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications – Chris F Carroll Mar 30 '15 at 15:56
ViewBag
- It returns Type Object.
- It is a
dynamic
property ofControllerBase
class. ViewBag
only works with .NET Framework 4.0 and above.- It does not require TypeCasting before use since
ViewBag
property isdynamic
in nature. ViewBag
returns Dynamic Type Object and its properties are alsodynamic
.- It is bit faster than
ViewData
.
ViewData
- It returns Key-Value Dictionary pair collection.
ViewData
is a dictionary object and it is property ofControllerBase
class.ViewData
is faster thanViewBag
.- Type Conversion code is required while enumerating since its a Dictionary Pair Collections.
ViewData
returns the object (type of key-value pair and value is type object, so you need to cast before use)
public ActionResult Index()
{
ViewBag.Name = "";
return View();
}
public ActionResult Index()
{
ViewData["Name"] = "Arun Prakash";
return View();
}
Calling in View
@ViewBag.Name
@ViewData["Name"]

- 17,736
- 16
- 35
- 75

- 1
- 1