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

前端 未结 2 1861
灰色年华
灰色年华 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: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;
        }
    

提交回复
热议问题