2

ViewData & ViewBag serve the same purpose of transferring data from Controller to View or between Views. The difference between them is the underlying implementation and the way we need to handle it as a result.(casting in case of ViewData etc.)

So, can there be any scenario where ViewData is preferred over ViewBag?

RKS
  • 1,370
  • 11
  • 20
  • 3
    FYI [What's the difference between ViewData and ViewBag?](http://stackoverflow.com/questions/4705426/whats-the-difference-between-viewdata-and-viewbag) –  Nov 29 '14 at 10:14
  • 1
    Thanx @StephenMuecke. I've voted to close the question. – RKS Nov 29 '14 at 10:20

1 Answers1

2

ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.

Being a wrapper it holds no data itself - it's just a shortcut for accessing ViewData. You have no reason to use the ViewData directly nowdays.

Mihai Dinculescu
  • 19,743
  • 8
  • 55
  • 70
  • 1
    ViewBag will be slower than ViewData; but probably not enough to warrant concern. See: http://stackoverflow.com/a/5079039/88409 Basically, the way ViewBag binds to ViewData ensures that (in spite of DLR CallSite caching) it cannot be faster than simply accessing ViewData directly, because the CallSite ends up binding to a method that just accesses ViewData directly, the way you would on your own. So ViewBag imposes an extra, although probably insignificant, level of indirection. – Triynko Jul 09 '15 at 13:00