Render partial from different folder (not shared)

前端 未结 10 1972
名媛妹妹
名媛妹妹 2020-11-29 17:12

How can I have a view render a partial (user control) from a different folder? With preview 3 I used to call RenderUserControl with the complete path, but whith upgrading to

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 17:13

    I've created a workaround that seems to be working pretty well. I found the need to switch to the context of a different controller for action name lookup, view lookup, etc. To implement this, I created a new extension method for HtmlHelper:

    public static IDisposable ControllerContextRegion(
        this HtmlHelper html, 
        string controllerName)
    {
        return new ControllerContextRegion(html.ViewContext.RouteData, controllerName);
    }
    

    ControllerContextRegion is defined as:

    internal class ControllerContextRegion : IDisposable
    {
        private readonly RouteData routeData;
        private readonly string previousControllerName;
    
        public ControllerContextRegion(RouteData routeData, string controllerName)
        {
            this.routeData = routeData;
            this.previousControllerName = routeData.GetRequiredString("controller");
            this.SetControllerName(controllerName);
        }
    
        public void Dispose()
        {
            this.SetControllerName(this.previousControllerName);
        }
    
        private void SetControllerName(string controllerName)
        {
            this.routeData.Values["controller"] = controllerName;
        }
    }
    

    The way this is used within a view is as follows:

    @using (Html.ControllerContextRegion("Foo")) {
        // Html.Action, Html.Partial, etc. now looks things up as though
        // FooController was our controller.
    }
    

    There may be unwanted side effects for this if your code requires the controller route component to not change, but in our code so far, there doesn't seem to be any negatives to this approach.

提交回复
热议问题