【问题标题】:ASP.NET Custom user control to add dynamicallyASP.NET 自定义用户控件动态添加
【发布时间】:2011-01-17 13:14:55
【问题描述】:

我很难将具有自定义用户控件的页面直接修改为 ASPX 页面,现在只需要在需要时动态加载它。用户控件通过 ASCX 文件确实有 html 和其他控件,并且在代码隐藏中有代码。

我已经阅读了多个页面,发现我不能直接实例化用户控件,但应该使用Page.LoadControl(...)。问题不在于编译,而是当页面加载控件时,ASCX 中的所有控件都为空,然后崩溃。

如何使用在 ASCX 和代码隐藏中动态包含代码的用户控件?

编辑:

我在(PageLoad 或 PagePreRender 或 PagePreInit)中所做的示例

      Control c = LoadControl(typeof(MyControl), null);
      myControl= (MyControl)c;
      myControl.ID = "123";
      myControl.Visible = false;
      Controls.Add(myControl);

MyControl 确实有例如 <div id="whatever" runat="server">... 并且在 MyControl 内部它将可见性设置为 True 或 False...但是当它这样做时,现在它崩溃了,因为“whatever” div 为 NULL。

【问题讨论】:

  • 你能发布你用来加载用户控件的代码吗?是通过 ajax 加载控件还是在整个页面加载时加载?
  • Page.LoadControl() 适合我。在处理哪个事件(Page.Init、Page.Load 等)时,您会加载它吗?
  • 页面加载和页面预渲染的行为与在 ASCX 用户控制文件中声明的 NULL 对象上的崩溃行为相同
  • 我测试了你的代码,我也得到了 null 但是当我在我的答案中使用代码时它工作正常。
  • 我会尝试用路径而不是像你那样的类型来加载控制

标签: asp.net dynamic webforms user-controls


【解决方案1】:

我所做的是使用Page_Init 中的Page.LoadControl 方法将自定义用户控件添加到页面上的占位符。

protected void Page_Init(object sender, EventArgs e)
{
    //MyControl is the Custom User Control with a code behind file
    MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");

    //UserControlHolder is a place holder on the aspx page
    // where I want to load the user control to
    UserControlHolder.Controls.Add(myControl);
}

这对我来说很好。

这是动态加载的用户控件的代码:

MyControl.ascx.cs

public partial class MyControl : System.Web.UI.UserControl
{
    protected void Page_Init(object sender, EventArgs e)
    {
        LiteralControl lit = new LiteralControl("Test Literal Control");
        Page.Controls.Add(lit);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        whatever.Visible = true;

        if (IsPostBack)
        {
            whatever.Visible = false;
        }
    }
}

【讨论】:

  • 您的解决方案不会引发我遇到的错误,但我看不到控件。如果我尝试简单地添加 new LiteralControl("TEST");我确实在源代码中看到了“测试”,但没有看到控件标记...
  • 如果您有一些文本直接进入 ASCX 是否有效?我将尝试生成一个小代码来解决我此时遇到的问题。
  • 它适用于一个简单的测试,但对于大型组件它不会在任何地方加载(但它不会崩溃)非常奇怪......
  • 我在某个地方出现了一个未显示的可见错误。我使用您的解决方案,效果很好 +1 和答案!
  • 为什么使用 Page_Init() 而不是 Page_Load()?
猜你喜欢
  • 2018-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-23
  • 1970-01-01
  • 2022-12-11
  • 2012-02-11
  • 1970-01-01
相关资源
最近更新 更多