简体   繁体   中英

Render control programmatically (using LoadControl) while adhering the page lifecycle

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

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM