我正在尝试使用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...
}
}