【问题标题】:Dynamically load user controls on button click, postback issue在按钮点击、回发问题上动态加载用户控件
【发布时间】:2013-01-22 23:30:39
【问题描述】:

我正在尝试在单击按钮时加载用户控件,但问题是,它在用户控件内的回发时消失了。

这是我加载控件的方式:

private bool IsUserControl
{
    get
    {
        if (ViewState["IsUserControl"] != null)
        {
            return (bool)ViewState["IsUserControl"];
        }
        else
        {
            return false;
        }
    }
    set
    {
        ViewState["IsUserControl"] = value;
    }
}


#region Usercontrols
private void CreateUserControlAllNews()
{
    Control featuredProduct = Page.LoadControl("path/usercontrol.ascx");
    plh1.Controls.Add(featuredProduct);
}

#endregion
protected void allNewsbtn_Click(object sender, EventArgs e)
{

    this.IsUserControl = true;
    if(IsUserControl)
    CreateUserControlAllNews();
}

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您需要在页面回发时重新加载控件。例如,

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsUserControl)
        {
            CreateUserControlAllNews();        
        }
    }
    
    private void CreateUserControlAllNews()
    {
        Control featuredProduct = Page.LoadControl("path/usercontrol.ascx");
        featuredProduct.ID = "1234";
        plh1.Controls.Add(featuredProduct);
    }
    

    【讨论】:

    • 感谢帮助。但问题是我有类似链接按钮的菜单,我想在每次点击时加载不同的用户控件。如果我在每个回发上加载控件,它们都会留在屏幕上。对不起我的英语不好,希望你能理解我的帖子。
    • 我在这里stackoverflow.com/a/14449305/296861回答了类似的问题。如果控件类型混合,则需要将 SortedDictionary 存储在 ViewState 中,而不是 List.
    【解决方案2】:

    当然它会消失,每个请求都会创建一个全新的页面实例,如果你不在那个回发上重新创建控件,那么它就不会存在。

    请参阅以下链接了解这个非常常见的问题。

    Singing eels

    Another SO question

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 2011-08-17
      • 1970-01-01
      相关资源
      最近更新 更多