Add user control after page is loaded
I am trying to add dynamically a user control I created to an aspx page after it is loaded. I tried sending an ajax request to a handler that used RenderControl function and sent back the control's html. I appended it to the DOM using javascript.
The problem is that some of the controls must go through开发者_运维问答 their Page_Load function and that doesn't happen when using RenderControl function.
Does anyone have any idea how can I do that?
try this:
System.Web.UI.Page page = new System.Web.UI.Page();
CustomUserControl userControl = page.LoadControl("~/control.ascx") as CustomUserControl;
if (userControl == null)
{
//error
}
userControl.ArticleId = id;
//call any other properties or methods you need
page.Controls.Add(userControl);
System.IO.StringWriter sw = new System.IO.StringWriter();
HttpContext.Current.Server.Execute(page, sw, false);
responseString = sw.ToString();
hope this will help!
Why dont you load and add the user control dynamically to the page?
I don't think you can do this that way.
Your controls don't go through their Page_Load, because they are not added to any control. All you are doing is rendering their html (using RenderControl) and loading it using javascript. There's no place for Page_Load event.
I would use UpdatePanel instead in that way:
<asp:UpdatePanel>
<ContentTemplate>
<asp:Panel ID="pnlDynamic" />
</ContentTemplate>
</asp:UpdatePanel>
and then in code behind add your dynamic controls to panel
pnlDynamic.Controls.Add(new YourControl());
精彩评论