Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is really the point of ViewBag?

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?

like image 746
Pinch Avatar asked Oct 11 '13 14:10

Pinch


2 Answers

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.

like image 146
usr Avatar answered Sep 21 '22 17:09

usr


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.

like image 25
James Avatar answered Sep 20 '22 17:09

James