1

Why do we have ViewBag and ViewData if they are doing the same thing in ASP.NET Core MVC? Is there anything which ViewBag can do and ViewData can't - or vice versa?

Any specific scenario when should I prefer one over the other?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ASR
  • 23
  • 6
  • 1
    ViewData is a dictionary of objects.ViewBag is a dynamic property, and is able to set and get value dynamically and able to add any number of additional fields without converting it to strongly typed. they are all used to transfer data from controller to view – Ruikai Feng Mar 23 '22 at 07:31
  • 1
    https://www.c-sharpcorner.com/blogs/viewdata-vs-viewbag-vs-tempdata-in-mvc1 – LazZiya Mar 23 '22 at 07:39

1 Answers1

1

They are similar, but the main difference is that ViewBag use dynamic types, allowing a less complex syntax.

ViewBag.Example=DateTime.Now;

<p>Result: ViewBag.Example.Year </p>

Against that, the same with ViewData could be:

ViewData["Example"]=DateTime.Now;

<p>Result: @((ViewData["Example"] As DateTime).Year) </p>

So with ViewData you need casting, and you can receive errors when perform a "renaming", and you won't have the aid of Intellisense, for example.

Additionally, it seems to be "slower" (but not enough to be a problem). Example: ViewBag vs ViewData performance difference in MVC?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Morcilla de Arroz
  • 2,104
  • 22
  • 29