3

I am coding an MVC internet application, and I have a question in regards to using the ViewBag.

In many of my controllers, I have SelectList objects, where the user can select an object. The object that is selected is a foreign key value for my model.

My question is this: Should I use ViewBag for this? How secure is the ViewBag? Should I use values in my ViewModel instead of the ViewBag?

Thanks in advance.

Simon
  • 7,991
  • 21
  • 83
  • 163
  • If your using a view model, then it makes sense to include your `SelectList` properties in the view model, but there is no difference between a model property and a ViewBag property in terms of 'security' –  Jan 16 '15 at 03:03

2 Answers2

3

Use your view model.

When the ViewBag was implemented (MVC 3) dynamic typing was new (.NET 4.0) and it was put in just as a side-option to ViewData or to quickly generate a view without the need for additional classes.

Any serious MVC project will take advantage of a model/viewmodel with a strongly typed view.

There are no security concerns with either because both essentially only exist through the controllers lifespan.

jamesSampica
  • 12,230
  • 3
  • 63
  • 85
1

There are no security concerns with ViewBag since it is disposed once rendered in the View.

I think the answer really should be "it depends". For example, if you have 6 collections required to populate dropdown lists aand you want to get the data posted back, you should definitely use a ViewModel for this. Since 6 collections will be hard to manage if they are stuffed in ViewBag with no strong typing in the view, especially if another developer comes along later needing to do maintenance to the view.

Generically everything should be done inside a view model. That's what a view model is. A class that you specifically define to meet the requirements of your view. Here is an image depecting when to Use TempData, ViewBag or ViewData

enter image description here

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47