How can we load usercontrol using a universal handler?

I want to load a user control using jquery ajax. One of the possible ones I found to load usercontrol through a common handler. Someone help me. here ajax code is used, which I use to call the control.

 <script type="text/javascript">
 function fillSigns() { 
                $.ajax({
                    url: "usercontrolhandler.ashx?control=signs.ascx",
                    context: document.body,
                    success: function (data) {                       
                        $('#signdiv').html(data);
                    }
                });
            }  
 </script>

and here is the code in the handler file

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        Page page = new Page();
        UserControl ctrl = (UserControl)page.LoadControl("~/" + context.Request["control"] + ".ascx");      
        page.Form.Controls.Add(ctrl);

        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter tw = new HtmlTextWriter(stringWriter);
        ctrl.RenderControl(tw);
        context.Response.Write(stringWriter.ToString());
    } 

This code causes an object error not found in the line below the line.

 page.Form.Controls.Add(ctrl);
+5
source share
2 answers

, page.Form null, . :

page.Controls.Add(ctrl);

HttpServerUtility.Execute :

StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(page, output, false);

, , Tip/Trick: Cool UI Templating Technique ASP.NET AJAX , UpdatePanel , .

+3

:

Page page = new Page {ViewStateMode = ViewStateMode.Disabled};
HtmlForm form = new HtmlForm { ViewStateMode = ViewStateMode.Disabled };
form.Controls.Add(ctrl);
page.Controls.Add(form);

StringWriter stringWriter = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(stringWriter);
page.RenderControl(tw);
context.Response.Write(stringWriter.ToString());
+1

All Articles