【问题标题】:Access Master Page public method from user control/class/page从用户控件/类/页面访问母版页公共方法
【发布时间】:2010-10-25 09:38:09
【问题描述】:

我要访问我的母版页上的方法。我有一个错误标签,我想根据从我的站点收到的错误消息对其进行更新。

public string ErrorText
{
    get { return this.infoLabel.Text; }
    set { this.infoLabel.Text = value; }
}

如何从我设置的用户控件或类中访问它?

【问题讨论】:

    标签: c# asp.net .net user-controls master-pages


    【解决方案1】:

    访问母版页:

    this.Page.Master
    

    那么您可能需要转换为母版页的实际类型,以便获得ErrorText 属性或使您的母版页实现包含此属性的接口。

    【讨论】:

    【解决方案2】:

    页面应该包含下一个标记:

    <%@ MasterType VirtualPath="~/Site.master" %>
    

    那么Page.Master 的类型不是MasterPage,而是您的母版页的类型,即:

    public partial class MySiteMaster : MasterPage
    {
        public string ErrorText { get; set; }
    }
    

    页面代码隐藏:

    this.Master.ErrorText = ...;
    

    另一种方式:

    public interface IMyMasterPage
    {
        string ErrorText { get; set; }
    }
    

    (将其放到 App_Code 或更好的类库中)

    public partial class MySiteMaster : MasterPage, IMyMasterPage { }
    

    用法:

    ((IMyMasterPage )this.Page.Master).ErrorText = ...;
    

    【讨论】:

    • 嘿,abatischev,我遇到了与 OP 完全相同的问题。我正要尝试界面路由,看起来很快 :) 只是好奇,在第一个示例中使用的 MasterType 在用户控件中是否有效?我知道这适用于子页面,想知道在实施选项 2 之前是否有办法让它与用户控件一起使用。谢谢!
    • @Chris:嗨!据我所知 - 不幸的是,它不适用于 UserControls。 UC 对父页面的母版页一无所知,只是对它们有一个引用:this.Page,this.Page.Master,所以选项 #2 是我唯一知道的一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 2010-11-25
    相关资源
    最近更新 更多