-1

Which is better to bring data from controller to view in .net MVC amongst ViewBag and ViewData ?

Anish
  • 33
  • 6

3 Answers3

1

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.

ANJYR
  • 2,583
  • 6
  • 39
  • 60
0

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

How ViewBag in ASP.NET MVC works

Community
  • 1
  • 1
Jason Evans
  • 28,906
  • 14
  • 90
  • 154
0

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.

Hadee
  • 1,392
  • 1
  • 14
  • 25