【问题标题】:User control not displayed after postback回发后不显示用户控件
【发布时间】:2013-05-17 09:46:13
【问题描述】:

我有一个 home.aspx 页面,其中有两个面板。在第一个面板中,我动态绑定了一个用户控件(用于在左侧显示 meiny),在第二个面板中,我显示了页面。 我在页面加载时动态绑定用户控件。

if (!IsPostBack)
    {
        UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
        Accordion1.Controls.Add(uc);          

    }

第一次加载页面时,我的usercontrol 已绑定并显示我的菜单,但是当我单击任何菜单项时它会隐藏(用户控件),

请帮助我,提前谢谢!

【问题讨论】:

    标签: c# asp.net user-controls


    【解决方案1】:

    把这行代码放在Page生命周期的Page_Init事件上。

    UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
    Accordion1.Controls.Add(uc);    
    

    正确方法:

    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);
    
    }
    

    如果你使用if (!IsPostBack),那么在回发后它不会被添加到页面中。第一时间就能看到页面上的控件。

    参考:
    ASP.NET Custom user control to add dynamically
    How to: Create Instances of ASP.NET User Controls Programmatically

    【讨论】:

    • 没关系。但是当我点击任何项目(我的用户控件中的菜单)时,它似乎重新绑定,实际上发生了闪烁,我该如何避免这种情况??
    • 这个闪烁是每次点击链接都会回发导致的,这是asp.net中的正常现象,注意你提到的网站使用了ajax技术,这样可以实现部分页面更新,并且页面将在不提交(发布)整个页面的情况下更新。 ref
    【解决方案2】:

    这是一个动态控件,必须在每次回发时重新创建并读取到页面中。

    所以这会起作用:

    //if (!IsPostBack)
    //{
        UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
        Accordion1.Controls.Add(uc);          
    //}
    

    【讨论】:

      【解决方案3】:

      动态控制不需要页面的!IsPostBack属性,去掉这个属性就可以使用

      UserControl uc = (UserControl)Page.LoadControl("~/settings/Links/Navigation.ascx");
      Accordion1.Controls.Add(uc);
      

      【讨论】:

        【解决方案4】:

        它必须在每次回发时加载。将用户控件加载代码保持在 if(!IsPostBack){} 之外。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-12
          • 1970-01-01
          • 1970-01-01
          • 2015-10-22
          • 2013-04-07
          相关资源
          最近更新 更多