简体   繁体   中英

Access Master Page public method from user control/class/page

I am to access a method on my master page. I have an error label which I want to update based on error messages I get from my site.

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

How can I access this from my user control or classes that I set up?

To access the masterpage:

this.Page.Master

then you might need to cast to the actual type of the master page so that you could get the ErrorText property or make your master page implement an interface containing this property.

Page should contain next markup:

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

then Page.Master will have not a type of MasterPage but your master page's type, ie:

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

Page code-behind:

this.Master.ErrorText = ...;

Another way:

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

(put it to App_Code or better - into class library)

public partial class MySiteMaster : MasterPage, IMyMasterPage { }

Usage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM