在遵循页面生命周期的同时以编程方式(使用LoadControl)呈现控件

时间:2013-02-11 13:47:56

标签: c# asp.net events webforms loadcontrol

我正在尝试使用LoadControl在代码中获取自定义控件,以便进行编程渲染。但是我注意到我的自定义控件的OnInit方法没有被调用。 我在这里错过了重要的一步吗?

//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();

这是上面代码的名称

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

1 个答案:

答案 0 :(得分:2)

因此,您正在对服务器进行PageMethods调用,并希望为自定义控件更新回送标记,就像它看起来一样。 PageMethods不执行生命周期,因此它永远不会触发OnInit事件处理程序。人们使用JQuery或HTTP处理程序使用了相同的技术,他们如何做到这一点的一些例子在这里:

相关问题