Does a child action share the same ViewBag with its "parents" action?

31,829

Solution 1

Child actions follow a different controller/model/view lifecycle than parent actions. As a result they do not share ViewData/ViewBag. If you want to pass parameters to a child action from the parent you could do this:

@Html.Action("Child", new { message = ViewBag.Message })

and in the child action:

public ActionResult Child(string message)
{
    ...
}

Solution 2

There is a way, but you have to create a custom abstract class as the base class for your razor views. Then expose whatever you need to from parent to child actions. This is how I get the root controller's ViewBag inside a class inheriting from WebViewPage

    private dynamic GetPageViewBag()
    {
        if (Html == null || Html.ViewContext == null) //this means that the page is root or parial view
        {
            return ViewBag;
        }
        ControllerBase controller = Html.ViewContext.Controller;

        while (controller.ControllerContext.IsChildAction)  //traverse hierachy to get root controller
        {
            controller = controller.ControllerContext.ParentActionViewContext.Controller;
        }
        return controller.ViewBag;
    }
Share:
31,829
NextStep
Author by

NextStep

Updated on February 19, 2020

Comments

  • NextStep
    NextStep about 4 years

    I am confused with this: I have an action ,say Parent ,and in the corresponding view file ,I have called a child action ,say Child ,both Parent and Child actions are in the same controller.

    and I need the Child action and the Parent action to share some data in the ViewBag.Now ,what I should do ?Here is my question:

    when I call the Child action in parent's view file ,I pass the viewbag to it like this: @Html.Action(ViewBag). in my child action ,I do this:

    public PartialViewResult Child(Object ViewBag)
    {
      //using the data in ViewBag
    }
    

    Is this the right way ? Does the viewbag object passed by reference or it is a different object then the original viewbag(more memory needed)?

    Or if the Child action is sharing the viewbag with its calling parent Action by default?

    From Darin Dimitrov's answer ,I knew that I can't do something like this:@Html.Action(ViewBag)

    But I really need to pass the child action muti-parameters,what can I do ?