I have noticed that in all the examples and tutorials on ASP.Net 5 (core) I have seen from Microsoft and the default Web Application template in VS 2015 use @ViewData["XXX"]
instead of @ViewBag.XXX
. Is this the, now, recommended way of passing data up from the controller instead of ViewBag
? I know that ViewBag
is a wrapper for ViewData
but in the old tutorials (ASP.NET 4.5) they use ViewBag
. If they are now encouraging developers to use ViewData
why the change?
The ViewData is a property of the Controller Base class, which returns a ViewDataDictionary object. The ViewDataDictionary as the name suggests is a dictionary object which allows us to store key-value pairs. The key must be a case-insensitive string.
ViewData and ViewBag are used for the same purpose -- to transfer data from controller to view. ViewData is nothing but a dictionary of objects and it is accessible by string as key. ViewData is a property of controller that exposes an instance of the ViewDataDictionary class. ViewBag is very similar to ViewData.
ViewData is a dictionary object and it is property of ControllerBase class. ViewData is faster than ViewBag . Type Conversion code is required while enumerating since its a Dictionary Pair Collections.
ViewBag is a property – considered a dynamic object – that enables you to share values dynamically between the controller and view within ASP.NET MVC applications.
Both are still valid. There is no specific guidance on the docs.asp.net github project. Although there is this discussion on docs.asp.net issues.
That links through to a comment from one the product team which says:
"Since ViewData (Dictionary) look-ups far out-perform ViewBag (dynamic) invocations, the last is probably the best choice."
So I'd say it purely a style choice based upon the fact that ViewData performs better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With