How do I call a method in a Master Page from a content's code-behind page?
Asked Answered
E

4

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?

Exhortation answered 13/6, 2011 at 15:54 Comment(0)
S
38

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.

Serif answered 13/6, 2011 at 15:57 Comment(1)
Check out Uwe Keim's answer first; I found it very simple to use.Missi
C
18

Use the MasterType directive like e.g.:

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

Then you can use the method like this:

Master.Method();
Cowbind answered 13/6, 2011 at 16:3 Comment(0)
D
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

Disrobe answered 13/6, 2011 at 15:58 Comment(1)
Can you add this as a static member at the top of your page?Exhortation
H
6
MyMasterPageType master = (MyMasterPageType)this.Master;
master.MasterPageMethod();
Healthful answered 13/6, 2011 at 15:56 Comment(2)
Can you add this as a static member at the top of your page?Exhortation
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; } }Healthful

© 2022 - 2024 — McMap. All rights reserved.