MVC ViewBag Best Practice

2019-01-08 12:21发布

For the ViewBag, I heard it was a no-no to use. I would assume have the content from the ViewBag should be incorporated into a view model?

Question:

  1. Is my assumption above the best practice. (Not to use a ViewBag and second to have it in the view model)

  2. Are there situations where a ViewBag is absolutely necessary?

9条回答
地球回转人心会变
2楼-- · 2019-01-08 13:13

I have found some use for ViewBag where there is common functionality across all pages, and the functionality does not depend on the page being shown. For example, say you are building StackOverflow. The job board appears on each page, but the jobs shown have nothing to do with the page (my usage was similar in concept). Adding a property to each ViewModel would be difficult and time consuming, and a lot of fluff to your tests. I don't think it is worth it in this situation.

I have used a base ViewModel class with the cross cutting data, but if you more than one (e.g., jobs & list of stack exchange sites), you either have to start stuffing extra data in, or some other abuse of a ViewModel, plus you need a ViewModel builder to populate the base data.

As for the magic strings problem, there are a lot of solutions. Constants, extension methods, etc.

With all that said, if you have something that is displayed on your page that depends on the context of the page, a ViewModel is your friend.

Erick

查看更多
乱世女痞
3楼-- · 2019-01-08 13:15
  1. No. Use ViewModels.
  2. No. If you design a perfect ViewModel, you never need a ViewBag.
查看更多
家丑人穷心不美
4楼-- · 2019-01-08 13:21

The issue with ViewBags and the recommended best practice boils down to compile time checking. ViewBags are just dictionaries and with that you get 'magic' strings, so if you end up changing the object type of one of the viewbag items or the key name you won't know until runtime, even if you precompile the views using <MvcBuildViews>true</MvcBuildViews>.

Sticking to view models is best, even if you have to alter them to fit a specific view now and again.

查看更多
登录 后发表回答