Question

In an ideal 'hello world' one should pass a strongly typed model back to the view.

return View(MyModel);

If things get sticky, we can create a

ViewModel

return View(MyViewModel);

ex.

MyViewModel

  1. MyModel
  2. Foo

I can avoid creating the whole ViewModel

and use a ViewBag in part.

ViewBag.Foo = Foo;
return View(MyModel);

I realize I will lose some strongly typed functionality

(ex. Intellisense)

in my View for that ViewBag.

Is this approach sloppy? against what MVC stands for?

If so, what is really the point of ViewBag?

Was it helpful?

Solution

The most useful use-case that I know of is out-of-band data like a message that might be shown on every page. An action filter could add that message to the ViewBag conditionally. You probably don't want to modify every view model class to hold that unrelated message because it might be a cross-cutting concern. An example of such a message/widget would be Stack Overflows outage announcements.

I do not recommend using ViewBag instead of a view model. The model class approach has the typical static typing advantages at the small cost of writing a class.

OTHER TIPS

This is a good question, personally, I don't really think there is any point - all it does is encourage "lazy" coding. dynamic objects have their uses, however, I don't see the ViewBag as being one of them, I would much rather use ViewData[]/ViewModel and get my type-safety in there, especially when I know what types I am dealing with.

I haven't encountered a scenario where it was beneficial to use ViewBag over the alternative (a correctly structured view model). Some of the other answers mention using it for a piece of data that needs to be displayed on every page. In this scenario you should create a base ViewModel class that all of your ViewModels inherit from. I use this structure to store the logged in user, etc.

In my opinion ViewBag serves one purpose: to make it easy and quick to give a product demo of ASP.NET MVC while writing minimal code. It is not the best way to structure code, but it sells the product.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top