Question

I'm trying to use LoadControl to get a custom control in code for programmatic rendering purposes. However I notice that the OnInit method of my custom control is not being called. Am I missing an essential step here?

//Loading the control
Page h = HttpContext.Current.Handler as Page;

UserControl userControl = (UserControl)h.LoadControl(pathToControl);
h.Controls.Add((Control)userControl);

//Rendering the control
StringWriter stringWriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter((TextWriter) stringWriter);
userControl.RenderControl(writer);
var result = stringWriter.ToString();

This is where the code above is called

[ScriptService]
public partial class Ajax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static object AjaxMethod(string productCode) {
        //here...
    }
}
Was it helpful?

Solution

So you are making a PageMethods call to the server, and want to stream back the markup for a custom control update, is what it looks like. PageMethods do not execute a lifecycle, therefore it will never fire the OnInit event handler. People have used this same technique using JQuery or an HTTP handler, and some examples of how they did it was here:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top