Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using ViewBag in MVC bad? [closed]

It seem like mvc 3 team decided to bring in a feature for dynamic data exchange between a controller and a view called the viewbag but it is A good thing against the strongly typed view we all know about? What are some of the positive and negative aspects to using the ViewBag versus using a strongly typed view?

like image 984
Rushino Avatar asked Jan 22 '11 03:01

Rushino


People also ask

Which is better ViewBag or ViewData?

In theory if properly implemented, the ViewBag would ultimately outperform the use of the ViewData dictionary because the binding of the expressions (e.g. ViewBag.

Does ViewBag expire?

ViewData/ViewBag - valid only for the duration of the current request. You set it in a controller action and use it in the view, then it disappears.

Is ViewBag slower than ViewData in MVC?

Yes, ViewBag is slower than ViewData in MVC.

When should I use ViewBag ViewData or TempData?

To summarize, ViewBag and ViewData are used to pass the data from Controller action to View and TempData is used to pass the data from action to another action or one Controller to another Controller.


1 Answers

The ViewBag is the same thing as ViewData in previous ASP.NET MVC 1 and 2. It just happens to be dynamic instead of needing to use it like a dictionary with keys. I don't think this will replace strongly typed views at all and in fact you should use Viewdata/Viewbag as little as possible. Always use strongly typed views whenever possible since it will lead to fewer errors if the names in your Viewdata/Viewbag change and make the HTML cleaner by not having ViewData casts all over the place.

like image 156
amurra Avatar answered Sep 20 '22 16:09

amurra