13

I'm looking for a way to (preferably) strongly type a master page from a user control which is found in a content page that uses the master page.

Sadly, you can't use this in a user control:

<%@ MasterType VirtualPath="~/Masters/Whatever.master" %>

I'm trying to access a property of the master page from the user control and would rather not have to pass the property from the master page to the content page to the user control because multiple content pages use the same user control. One change, one place whatnot.

Bryan Denny
  • 27,363
  • 32
  • 109
  • 125
  • What about adding a property to the user control called "Master" and then just pass a reference when the control is declared? – Kevin Jan 06 '09 at 14:26
  • I'm trying to avoid having to pass any references through the control, but good suggestion. – Bryan Denny Jan 06 '09 at 14:33

4 Answers4

18

Try Page.Master.

Whatever whatev = (Whatever)Page.Master;

You'll have to make sure you add the proper using statements to the top of your file, or qualify the Master page type inline.

One potential gotcha is if this control is used by a different page whose master page is NOT the same type. This would only get caught at runtime.

rswank
  • 133
  • 1
  • 8
Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
  • 1
    Just to clarify Whatever (above) is the actual type of your master page. So, with the default master page type name you could use... SiteMaster masterPage = (SiteMaster)Page.Master; http://stackoverflow.com/questions/4013343/access-master-page-public-method-from-user-control-class-page – DeveloperDan May 16 '13 at 20:59
0

The best way to do it that I've found is actually to build a custom class that is based off of UserControl, give it a Master property with a get accessor that fishes through the this.Page.Parent until it stops encountering master pages (If you are nesting, this step is unnecessary otherwise) and then return that web control as the type of the master page you want to use. Then, when you add a new user control, change it's base class to the name of your custom class. The .Master property will be accessible and cast properly as the master page you want it to use.

0

Have you tryed Page.FindControl("name") on the usercontrol?

Sergio
  • 8,125
  • 10
  • 46
  • 77
0

In VB all I needed to do was change this:

Dim lAuthLevel As Integer = Master.MasterContact.AuthenticationLevel

to this:

Dim lAuthLevel As Integer = CType(Me.Page.Master, main).MasterContact.AuthenticationLevel

So all references of Master become Ctype(Me.Page.Master, typeofMaster)

Where is in this case the word "main" - get that from the declaration at the top of the master page. e.g.

So "main" in this case :)

user2728841
  • 1,333
  • 17
  • 32