How to include a partial view inside a webform

后端 未结 7 2265
灰色年华
灰色年华 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:48

    I had a look at the MVC source to see if I could figure out how to do this. There seems to be very close coupling between controller context, views, view data, routing data and the html render methods.

    Basically in order to make this happen you need to create all of these extra elements. Some of them are relatively simple (such as the view data) but some are a bit more complex - for instance the routing data will consider the current WebForms page to be ignored.

    The big problem appears to be the HttpContext - MVC pages rely on a HttpContextBase (rather than HttpContext like WebForms do) and while both implement IServiceProvider they're not related. The designers of MVC made a deliberate decision not to change the legacy WebForms to use the new context base, however they did provide a wrapper.

    This works and lets you add a partial view to a WebForm:

    public class WebFormController : Controller { }
    
    public static class WebFormMVCUtil
    {
    
        public static void RenderPartial( string partialName, object model )
        {
            //get a wrapper for the legacy WebForm context
            var httpCtx = new HttpContextWrapper( System.Web.HttpContext.Current );
    
            //create a mock route that points to the empty controller
            var rt = new RouteData();
            rt.Values.Add( "controller", "WebFormController" );
    
            //create a controller context for the route and http context
            var ctx = new ControllerContext( 
                new RequestContext( httpCtx, rt ), new WebFormController() );
    
            //find the partial view using the viewengine
            var view = ViewEngines.Engines.FindPartialView( ctx, partialName ).View;
    
            //create a view context and assign the model
            var vctx = new ViewContext( ctx, view, 
                new ViewDataDictionary { Model = model }, 
                new TempDataDictionary() );
    
            //render the partial view
            view.Render( vctx, System.Web.HttpContext.Current.Response.Output );
        }
    
    }
    

    Then in your WebForm you can do this:

    <% WebFormMVCUtil.RenderPartial( "ViewName", this.GetModel() ); %>
    

提交回复
热议问题