【问题标题】:How do I get access to master page properties via user control markup?如何通过用户控件标记访问母版页属性?
【发布时间】:2014-06-27 11:08:43
【问题描述】:

我一直在搜索互联网,我发现大多数解决了从用户控件代码访问母版页属性的问题。但是我找不到用户控件可以访问标记内的母版页属性的解决方案。

背景:

母版页动态地将用户控件添加到页面上。 母版页有两个属性,用户控件需要通过标记访问它们。

这里有一些代码来代表我的问题:

母版页属性背后的代码:

public IModule Module
    {
        get
        {
            return MyContext.Current.Module;
        }
    }

    public IDictionary<string, object> Arguments
    {
        get
        {
            return MyContext.Current.Arguments;
        }
    }

母版页在后面的代码中动态添加到控件(必须在母版页的代码后面动态添加):

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

            if (!(Page is VehicleForm) && !(Page is VsrManageForm) && !(Page is VpbManageForm))
            {
                MenuTab view = (MenuTab)this.LoadView(plhMenu, "~/Controls/MenuTab.ascx", "", MyContext.Current.Module);
            }
        }

用户控件的标记:

<web:FlowLink class="tools__lnk" arguments="<%# Arguments %>" id="flowLink1" runat="server" contextmodule='<%# Module %>' flowcall="FavouritesView" title="" rel="nofollow" ClientIDMode="Omitted">Shortlist</web:FlowLink>
<web:FlowLink class="tools__lnk" arguments="<%# Arguments %>" id="flowLink2" runat="server" contextmodule='<%# Module %>' flowcall="CompareView" title="" rel="nofollow" ClientIDMode="Omitted">Compare</web:FlowLink>
<web:FlowLink class="tools__lnk" arguments="<%# Arguments %>" id="flowLink5" runat="server" contextmodule='<%# Module %>' flowcall="UserView" title="" rel="nofollow" ClientIDMode="Omitted">Account</web:FlowLink>

错误:

Compiler Error Message: CS0103: The name 'Arguments' does not exist in the current context

问题: 如何从用户控件访问 和 母版页属性?

【问题讨论】:

    标签: c# html asp.net


    【解决方案1】:

    可能(虽然还没有测试过)做这样的事情:

    arguments="<%# ((MasterPageType)this.Page.Master).Arguments %>"
    

    虽然看起来不太对劲。您可能想要重新设计您控制获取数据的方式。或者至少在代码后面的某个地方做同样的事情,并验证当前的母版页是否是预期的类型。

    更新。 OP 使用的最终解决方案结合了上述想法,并导致在控件中声明如下属性:

    public IDictionary<string, object> Arguments
    {
        get
        {
            MasterPageType master = this.Page.Master as MasterPageType;
            if (master != null)
            {
                return master.Arguments;
            }
            else
            {
                return null;
            }
        }
    }
    

    【讨论】:

    • 你会建议什么重新设计?
    • @GIVE-ME-CHICKEN,嗯,这在很大程度上取决于您的需求和要求,我不知道。但是至少,就像我说的那样,不要以声明方式初始化控件的这些属性,而是在代码后面执行此操作,以确保母版页是您期望的类型
    • 你绝对帮助我朝着正确的方向前进。如果您编辑帖子以提及将相同的属性(从母版页)添加到用户控件的代码后面,并更改 get 函数以返回母版页的属性(例如 get { return (MasterPageType)this.Page.Master) .Arguments } ),然后我将标记为答案。
    • @GIVE-ME-CHICKEN,完成。请注意,我添加了类型检查 - 如果您还没有这样做,强烈建议您这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 2011-03-17
    • 2013-03-24
    • 1970-01-01
    • 2016-02-27
    相关资源
    最近更新 更多