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
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?
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.
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.
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