What is really the point of ViewBag?
Asked Answered
D

3

5

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?

Dalrymple answered 11/10, 2013 at 14:18 Comment(1)
It's for the things you forgot to put in your view model ;-)Pegboard
D
5

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.

Doha answered 11/10, 2013 at 14:20 Comment(5)
Very interesting, makes for sense now. Thanks!Dalrymple
I never seen Stack Overflows outage before :)Linguistics
You don't remember that famous SO Outage on Thurs Oc 10 that took place from 12:02:00:01AM - 12:02:00:02AM? @MuraliDalrymple
I thought it was a delay from our proxy server. But i dont see the message, since the page itself was not loaded :(Linguistics
They sometimes announce short read-only periods when they maintain the databases.Doha
S
1

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.

Selfrealization answered 11/10, 2013 at 14:34 Comment(1)
viewdata isnt really any more typesafeEpicurus
M
1

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.

Milquetoast answered 11/10, 2013 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.