How to include a partial view inside a webform

后端 未结 7 2249
灰色年华
灰色年华 2020-11-28 01:07

Some site I\'m programming is using both ASP.NET MVC and WebForms.

I have a partial view and I want to include this inside a webform. The partial view has some code

7条回答
  •  死守一世寂寞
    2020-11-28 01:42

    This is great, thanks!

    I'm using MVC 2 on .NET 4, which requires a TextWriter gets passed into the ViewContext, so you have to pass in httpContextWrapper.Response.Output as shown below.

        public static void RenderPartial(String partialName, Object model)
        {
            // get a wrapper for the legacy WebForm context
            var httpContextWrapper = new HttpContextWrapper(HttpContext.Current);
    
            // create a mock route that points to the empty controller
            var routeData = new RouteData();
            routeData.Values.Add(_controller, _webFormController);
    
            // create a controller context for the route and http context
            var controllerContext = new ControllerContext(new RequestContext(httpContextWrapper, routeData), new WebFormController());
    
            // find the partial view using the viewengine
            var view = ViewEngines.Engines.FindPartialView(controllerContext, partialName).View as WebFormView;
    
            // create a view context and assign the model
            var viewContext = new ViewContext(controllerContext, view, new ViewDataDictionary { Model = model }, new TempDataDictionary(), httpContextWrapper.Response.Output);
    
            // render the partial view
            view.Render(viewContext, httpContextWrapper.Response.Output);
        }
    

提交回复
热议问题