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?

2
  • 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 Commented Mar 23, 2022 at 7:31
  • 1
    c-sharpcorner.com/blogs/viewdata-vs-viewbag-vs-tempdata-in-mvc1 Commented Mar 23, 2022 at 7:39

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

2 Comments

It means, if we want speed, we should use ViewData, and if we use Ease of use we should use ViewBag.
Yes, we could say that ViewBag is a wrapper over ViewData, although performance's difference is almost irrelevant,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.