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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With