Calling master functions and properties are a decade old question and the usual way is to define the master type in the content page i.e
<%@ MasterType VirtualPath="~/Site.master" %>
. This works well however it creates a strong dependency with one master type. How about changing the master dynamically from the content page. The situation gets worse. In that time, the masters have to be accessed to a common contract. So that whenever the master changes and sticks to the contract, the agreements never fails. The contract could be a super class, abstract class or an interface.
This sample code is about use of an interface. Have a simple interface in the
App_code folder:
public interface ICommonMasterFunctions
{
void setPageNumber(string number);
}
Have a label in the master page:
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
Implement the interface to all the masters required.
public partial class SiteMaster : System.Web.UI.MasterPage,ICommonMasterFunctions
{
public void setPageNumber(string number)
{
Label1.Text = "You are on the page " + number.ToString();
}
}
Now you can pass the page number from the content page:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ICommonMasterFunctions master = (ICommonMasterFunctions)this.Master;
master.setPageNumber("5");
}
}
As all the required masters agreed on this contract, changing the master doesn't need to change the code. This gives some flexibility.