C# – ASP.Net Web Forms – How to set properties of MasterPage from page and user controls

asp.netcmaster-pagesuser-controls

I have two master pages which are used by different content pages.
I want to set master page properties from content page, so that master page can show some changes based on those values. And then I also need to access those master page properties in user controls added in master page to reflect some changes. How to achieve that?

I have found a way how to set master page properties from content page by adding <%@ MasterType VirtualPath="/Site.master" %> and then using **Master.property=value** but not sure about how to access user control. Any ideas?

Best Answer

You can create a base class form which your master pages inherit from that includes the properties you're looking to store:

abstract public class MasterPageBase : System.Web.UI.MasterPage
{
    public string Prop1
    {
        get { return "Some Value"; }
    }
}

From your UserControl, you can then access the properties as follows:

MasterPageBase masterPage = (MasterPageBase)this.Page.Master;
string strTest = masterPage.Prop1; // "Some Value"