Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ViewData the new standard over ViewBag for ASP.Net 5 (core)?

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?

like image 483
Matthew Verstraete Avatar asked Jan 06 '16 14:01

Matthew Verstraete


People also ask

What is ViewData in asp net core?

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.

What is ViewBag and ViewData in asp net core?

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.

What is better ViewData or ViewBag?

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.

What is ViewBag in asp net core?

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.


1 Answers

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.

like image 147
Martin Beeby Avatar answered Sep 18 '22 17:09

Martin Beeby