从用户控制/类/页访问主页面公共方法

问题描述:

我要访问我的母版页上的方法。我有一个错误标签,我想根据从我的网站获得的错误消息进行更新。从用户控制/类/页访问主页面公共方法

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

如何从我的用户控件或我设置的类访问此选项?

页应该包含下一个标记:

<%@ 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 = ...; 
+0

嘿abatischev,我有完全一样的问题,因为OP。我即将尝试接口路由,看起来很快:)只是好奇,是在用户控件中有效的第一个示例中使用的MasterType?我知道这对孩子页面正常工作,想知道是否有一种方法来实现选项2之前,与用户控件一起工作。谢谢! – clamchoda 2012-01-17 18:19:00

+0

@Chris:嗨!据我所知 - 不幸的是,它不适用于UserControls。 UC对父页面的母版页一无所知,只是对它们有一个引用:this.Page,this.Page.Master,所以选项#2是我唯一知道的 – abatishchev 2012-01-18 07:19:47

要访问母版:

this.Page.Master 

,那么你可能需要转换到实际类型的母版页,这样你可以得到ErrorText属性或让你的母版页实施包含此属性的界面。

+0

如何使用this.Page.Master从类。它似乎不适合我。 – Churchill 2010-10-25 10:15:25

+0

http://stackoverflow.com/questions/416691/how-to-reference-a-master-page-from-a-user-control – DeveloperDan 2013-05-16 21:03:42