Modifying MVC 3 ViewBag in a partial view does not persist to the _Layout.cshtml

后端 未结 10 1845

I am using MVC 3 with the Razor view engine. I want to set some values in the ViewBag inside a Partial View and want retrieve those values in my _Layout.cshtml. For exampl

10条回答
  •  眼角桃花
    2020-12-08 13:58

    I also had this problem, and couldn't find any neat and obvious solution.

    The solution I came up with was to implement an Html extension method that returns a 'PageData' class that you define, containing whatever data you need:

        [ThreadStatic]
        private static ControllerBase pageDataController;
        [ThreadStatic]
        private static PageData pageData;
    
        public static PageData GetPageData(this HtmlHelper html) {
            ControllerBase controller = html.ViewContext.Controller;
            while (controller.ControllerContext.IsChildAction) {
                controller = controller.ControllerContext.ParentActionViewContext.Controller;
            }
            if (pageDataController == controller) {
                return pageData;
            } else {
                pageDataController = controller;
                pageData = new PageData();
                return pageData;
            }
        }
    

    It finds the top-level controller for the current request, and returns the same PageData object every time the method is called within the same HTTP request. It creates a new PageData object the first time it is called in a new HTTP request.

提交回复
热议问题