How to include a partial view inside a webform

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

    FWIW, I needed to be able to render a partial view dynamically from existing webforms code, and insert it at the top of a given control. I found that Keith's answer can cause the partial view to be rendered outside the tag.

    Using the answers from Keith and Hilarius for inspiration, rather than render direct to HttpContext.Current.Response.Output, I rendered the html string and added it as a LiteralControl to the relevant control.

    In static helper class:

        public static string RenderPartial(string partialName, object model)
        {
            //get a wrapper for the legacy WebForm context
            var httpCtx = new HttpContextWrapper(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(), new StringWriter());
    
            // This will render the partial view direct to the output, but be careful as it may end up outside of the  tag
            //view.Render(vctx, HttpContext.Current.Response.Output);
    
            // Better to render like this and create a literal control to add to the parent
            var html = new StringWriter();
            view.Render(vctx, html);
            return html.GetStringBuilder().ToString();
        }
    

    In calling class:

        internal void AddPartialViewToControl(HtmlGenericControl ctrl, int? insertAt = null, object model)
        {
            var lit = new LiteralControl { Text = MvcHelper.RenderPartial("~/Views/Shared/_MySharedView.cshtml", model};
            if (insertAt == null)
            {
                ctrl.Controls.Add(lit);
                return;
            }
            ctrl.Controls.AddAt(insertAt.Value, lit);
        }
    

提交回复
热议问题