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

前端 未结 2 1848
灰色年华
灰色年华 2020-12-05 17:13

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

相关标签:
2条回答
  • 2020-12-05 18:00

    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)
    {
        ...
    }
    
    0 讨论(0)
  • 2020-12-05 18:14

    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;
        }
    
    0 讨论(0)
提交回复
热议问题