如何通过用户控制标记访问母版页属性?

时间:2014-06-27 11:08:43

标签: c# html asp.net

我一直在搜索互联网,大多数情况下我发现从后面的用户控件代码中访问主页面属性的问题。但我无法找到一个解决方案,其中用户控件可以访问标记中的母版页属性。

背景

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

以下是一些代表我的问题的代码:

主页背后的代码:

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

问题: 如何访问&lt;%#Arguments%&gt;和&lt;%#Module%&gt;来自用户控件的母版页属性?

1 个答案:

答案 0 :(得分:2)

可能有可能(尽管没有测试过)做这样的事情:

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;
        }
    }
}
相关问题