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?
How do I call a method in a Master Page from a content's code-behind page?
Asked Answered
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.
Check out Uwe Keim's answer first; I found it very simple to use. –
Missi
Use the MasterType
directive like e.g.:
<%@ MasterType VirtualPath="~/masters/SourcePage.master" %>
Then you can use the method like this:
Master.Method();
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
Can you add this as a static member at the top of your page? –
Exhortation
MyMasterPageType master = (MyMasterPageType)this.Master;
master.MasterPageMethod();
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.