Keith Costa
Keith Costa

Reputation: 1793

Call master page function from user control?

After searching Google I found one way to call a master page function from a user control:

  1. Create an interface that includes your method.
  2. Implement the interface in your master page
  3. From your control, reference this.Page.Master via the interface type.
  4. Call your method.

This is a good approach, but I don't know that can I call a master page static function in this way.

Another approach is :

// this is also good.
((MyMaster)this.Page.Master).MyFunction(); 

But I heard that this can also be done through an event.

1) Could someone show me how I could call a master page function from a user control through an event? 2) Also, how can I call a master page static function through a common interface way which I explained above.

Upvotes: 0

Views: 3388

Answers (2)

Nick Rolando
Nick Rolando

Reputation: 26167

In your content page, use the MasterType directive to generate the Master type. Then you can use the exposed Master property in the content page without casting. If you want to call a static function in the master from the content, you need to call it using the name of the master's code-behind class (since it is static)

content page:

<%@ Page MasterPageFile="~/dir1/master1.master" ....... %>
<%@ MasterType VirtualPath="~/dir1/master1.master" %> <!--This technique might change between .net versions. This is testing on 3.5-->

content page.cs

this.Master.nonStaticFunc();
dir1_master1.staticFunc();

Upvotes: 1

adam0101
adam0101

Reputation: 30995

I think it'd be better to have your user control raise an event and have your page listen for the event and then call the master page function. Controls shouldn't have any knowledge of the things that implement them - including whether or not the page has a master page.

Upvotes: 3

Related Questions