Alex Rivera | Logout

MVC ViewBag Best Practice

Asked 2012-06-29T12:45:15.987
33

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?

Edit
Report

1 Answer

2

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

answered 2012-06-29T18:44:59.080

Your Answer