Which is better to bring data from controller to view in .net MVC amongst ViewBag and ViewData ?
-
And http://stackoverflow.com/questions/7993263/viewbag-viewdata-and-tempdata – David Spence Nov 08 '15 at 19:07
3 Answers
Both the ViewData
and ViewBag
objects are great for accessing data between the controller and view.
The ViewBag
objects lets you add dynamic
properties to it which makes it a very verstile tool.So dynamic
object, meaning you can add properties to it in the controller.It achieves the same goal as ViewData
and should be avoided in favour of using strongly typed view models.

- 2,583
- 6
- 39
- 60
ViewBag
is a dynamic wrapper around ViewData
.
So with ViewData you can do
ViewData["MyData"] = "Hello World"
You can achieve the same result using
ViewBag.MyData = "Hello World"
Since ViewBag
is dynamic
, you can access properties that may not actually exist e.g. ViewBag.NothingToSeeHere
and the code will still compile. It may hit an exception when you run that line of code, but the property is not resolved until runtime.
More information can be found here

- 1
- 1

- 28,906
- 14
- 90
- 154
As Jason mentioned, "ViewBag is a dynamic wrapper around ViewData".
For the most part, there isn’t a real technical advantage to choosing one syntax over the other.ViewBag is just syntactic sugar that some people prefer over the dictionary syntax.
Although there might not be a technical advantage to choosing one format over the other, there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed 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 be aware of is that dynamic values cannot be passed in as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order for it 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 value to a specifi c type: (string) ViewBag.Name.

- 1,392
- 1
- 14
- 25