0

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 4

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Yeah you can.

Just set a value for a ViewBag item in your controller and reference it in in your partials.

e.g.

Controller Action:

public ActionResult Index()
{
    ViewBag.Test = "Something";
    return View();
}

View:

<div>@Html.Partial("_Test")</div>

Partial:

@ViewBag.Test

Comments

0

I'm not 100% sure, but i belive that the ViewBag is shared between all Views.

If that doesn't work for you, can't you instead pass the shared variables in a class from your Controller to the partial views?

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.