I have a layout that contain three Partial Views. Is possible to share ViewBag variables between each one? If not, how can I share some information of one partial view to the other two? Thanks
4 Answers
I would do it by passing it into the view so its more explicit of its dependencies.
Pass the common data from the parent model into the ViewModel of the partials either by itself as the Model or as part of the child model.
@Html.Partial("Partial1", Model.CommonData)
@Html.Partial("Partial2", Model.CommonData)
@Html.Partial("Partial3", Model.CommonData)
Comments
Yes, ViewBag is usable in all partials, however, you have to be conscious of the fact that you may not be able to predict the order in which a partial will execute. That is, if one partial depends on a variable being set in another partial, you can't guarantee that the other partial will render before that one.
Best practice would be to set all variables in the controller, and then only consume them in the view.