19

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Adrian S
  • 1,007
  • 4
  • 12
  • 26

4 Answers4

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
19

Use the MasterType directive like e.g.:

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

Then you can use the method like this:

Master.Method();
Phil
  • 153
  • 5
  • 15
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
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
  • Can you add this as a static member at the top of your page? – Adrian S Jun 14 '11 at 20:16
  • 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