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...
}
}