I have a public method in my ASP.NET Master Page. Is it possible to call this from a content page, and if so what are the steps/syntax?
Asked
Active
Viewed 4.0k times
4 Answers
37
From within the Page
you can cast the Master
page to a specific type (the type of your own Master
that exposes the desired functionality), using as
to side step any exceptions on type mismatches:
var master = Master as MyMasterPage;
if (master != null)
{
master.Method();
}
In the above code, if Master
is not of type MyMasterPage
then master
will be null
and no method call will be attempted; otherwise it will be called as expected.

Grant Thomas
- 44,454
- 10
- 85
- 129
-
4Check out Uwe Keim's answer first; I found it very simple to use. – Tim Dec 19 '13 at 17:58
19
Use the MasterType
directive like e.g.:
<%@ MasterType VirtualPath="~/masters/SourcePage.master" %>
Then you can use the method like this:
Master.Method();
11
You can simply do like...
MasterPageClassName MasterPage = (MasterPageClassName)Page.Master;
MasterPage.MasterMethod();
Check for Details ACCESS A METHOD IN A MASTER PAGE WITH CODE-BEHIND

Muhammad Akhtar
- 51,913
- 37
- 138
- 191
6
MyMasterPageType master = (MyMasterPageType)this.Master;
master.MasterPageMethod();

George Duckett
- 31,770
- 9
- 95
- 162
-
-
Not a static member, because the master page is specific to the page currently handling the request. You could make an instance property for the master page though: `private MyMasterPageType master { get { return (MyMasterPageType)this.Master; } }` – George Duckett Jun 14 '11 at 20:20