Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can we load usercontrol using generic handler?

i want to load a user control using jquery ajax. One possible i found is to load usercontrol through generic handler. Anyone help me plsss. here the ajax code i am using 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 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 raises object reference not found error at below shown line.

 page.Form.Controls.Add(ctrl);
like image 441
Dileep Paul Avatar asked Oct 12 '22 09:10

Dileep Paul


1 Answers

It seems page.Form is null here, that's why you've got a null reference exception. You could add your user control to the page's control collection instead:

page.Controls.Add(ctrl);

You could also use HttpServerUtility.Execute method for page rendering:

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

And finally take a look onto Tip/Trick: Cool UI Templating Technique to use with ASP.NET AJAX for non-UpdatePanel scenarios article by Scott Guthrie which covers your problem.

like image 110
Oleks Avatar answered Oct 14 '22 07:10

Oleks