MVC 5 ViewBag security

六月ゝ 毕业季﹏ 提交于 2021-01-27 14:29:05

问题


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

enter image description here



来源:https://stackoverflow.com/questions/27976615/mvc-5-viewbag-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!