问题
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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/27976615/mvc-5-viewbag-security