asp.net-mvcasp.net-coreviewbagviewdata

Why do we have ViewBag and ViewData, if they are doing the same thing in ASP.NET Core MVC


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?


Solution

  • 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?