开发者

how can we load usercontrol using generic handler?

开发者 https://www.devze.com 2023-02-20 19:46 出处:网络
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.

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);
                    }
       开发者_如何学Go         });
            }  
 </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);


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.


Try this:

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

then:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号