动态加载用户控件 - 回发问题
我试图在 aspx 页面上动态加载用户控件,但是它可以工作,但我遇到回发问题?我在用户控件上有一个图像按钮,我想显示图像,但是当我单击按钮时,页面刷新并且不显示图像?我在 aspx 页面和后端代码上有一个占位符,我有这个:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Control uc = Page.LoadControl("~/UserControls/Mycontrol.ascx");
placeholder1.Controls.Add(uc);
}
}
我需要在 page_preinit 或 page_init 中执行某些操作吗?
Im trying to load a usercontrol dynamically on a aspx page however it works but i get postback issues?? I have a image button on usercontrol which I want to show a image however when i do click on button the page refreshes and does not show image?. I have a placeholder on aspx page and backend code i have this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Control uc = Page.LoadControl("~/UserControls/Mycontrol.ascx");
placeholder1.Controls.Add(uc);
}
}
Do i need to do something in page_preinit or page_init ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该始终在每次回发时重新加载 Page_init 上的用户控件。
You should always reload the user control on the Page_init on each post back.
添加到页面的动态控件必须在每次回发时添加,而不仅仅是第一个回发。删除
!IsPostBack
条件。其次,它们必须在 init 或 preinit 期间添加,因为这样,视图状态将被正确捕获和恢复(ASP.NET 在 init 和 load 事件之间恢复视图状态)。Dynamic controls added to the page must be added on every postback, not just the first one. Remove the
!IsPostBack
condition. Secondly, they have to be added during init or preinit, because that way, viewstate will be captured and restored properly (ASP.NET restores viewstate between init and load events).给控件一个ID,并在Page_init中加载控件
Give the control an ID and also load the control in Page_init