【问题标题】:Dynamically adding Content blocks to Masterpage fails after Master.FindControl在 Master.FindControl 之后,将内容块动态添加到 Masterpage 失败
【发布时间】:2023-03-29 07:10:01
【问题描述】:

我遇到了一个对我来说毫无意义的奇怪问题。我正在尝试在页面上动态设置 MasterPage 内容控件。我可以很好地使用以下代码:

    protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);

        MasterPageFile = "~/MasterPages/Default.master";

        string existantContentPlaceHolderID = "ContentPlaceHolder1";
        string nonExistantContentPlaceHolderID = "foo";

        //Control c = Master.FindControl(existantContentPlaceHolderID);
        //Control c1 = Master.FindControl(nonExistantContentPlaceHolderID);

        TextBox t = new TextBox
                        {
                            Text = "Text"
                        };

        ITemplate iTemplate = new GenericITemplate(container => container.Controls.Add(t));

        AddContentTemplate(existantContentPlaceHolderID, iTemplate);

    }

    public delegate void InstantiateTemplateDelegate(Control container);

    public class GenericITemplate : ITemplate
    {
        private readonly InstantiateTemplateDelegate m_instantiateTemplate;

        public void InstantiateIn(Control container)
        {
            m_instantiateTemplate(container);
        }

        public GenericITemplate(InstantiateTemplateDelegate instantiateTemplate)
        {
            m_instantiateTemplate = instantiateTemplate;
        }
    }

这很好用,除了我希望能够在调用 AddContentTemplate 之前仔细检查 MasterPage 上是否存在 contentPlaceHolderID,因为如果添加指向不存在 ContentPlaceHolder 的 Content 控件,页面将引发错误。

我遇到的问题是,在上面的示例中,当我调用注释的 Master.FindControl 行之一时,TextBox 不再呈现。

有没有人知道为什么会这样......我无法确定正在发生的事情。

谢谢, 最大

【问题讨论】:

    标签: c# asp.net master-pages itemplate


    【解决方案1】:

    问题在于 AddContentTemplate 只是将其参数记录在一个哈希表中,以便在创建时与母版页实例组合。在创建母版页后调用它不会做任何事情,读取 Master 属性会导致创建母版页。

    我能看到的最佳方法是使用 LoadControl 创建母版页的单独实例,您可以在不影响页面自己的 Master 属性的情况下对其进行检查...

    MasterPage testMaster = (MasterPage) LoadControl( MasterPageFile );
    Control c = testMaster.FindControl(existantContentPlaceHolderID);
    

    创建第二个实例会产生一些开销,但对我来说是否值得担心并不是很明显。

    【讨论】:

    • hmm...这很有趣,我没有想到访问 Master 会开始做一些事情,但这确实是有道理的。我只有有限数量的母版页,所以我会尝试您的解决方案,但将加载的控件放入缓存中,并将缓存依赖设置回主文件...
    猜你喜欢
    • 2023-04-05
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多