views:

225

answers:

5

How do I reference a master page from an ASP.NET webform? The following statement does not work:

this.MasterPage.Page.Title = "My Title";
+6  A: 

In your aspx, below the Page directive, write:

<%@ MasterType VirtualPath="YourMasterFile" %>

And then from your code, write Master. anything that you want to use, for example:

Master.Title = "My Title";
fbinder
+2  A: 

you have to cast this.MasterPage into the type of masterpage you have, and then you can access it as you'd expect

var mp = this.MasterPage as MyMasterPageType;
mp.Property = value... etc
Matthew Steeples
A: 

In your code write :

Dim masterpage As New MasterPage
    masterpage = CType(masterpage, MasterPage)

and in your source code where the language is defined and etc type this

MasterPageFile="~/MasterPage.master"

If you write in C#

 MasterPage masterpage = new MasterPage();
masterpage = (MasterPage)masterpage;
Eric
+1  A: 

From the Page you can use the Master property and cast this to your master page. i.e. (MyMasterPage)this.Master. However, whenever I attempt to do this I always check it can be cast first so I normally end up with something like...

MyMasterPage master;
if (this.Master is MyMasterPage)
{
    master = (MyMasterPage)this.Master
    //do stuff with master.
}

If all you are wanting to do is change the title then you can just use Page.Title and make sure that the head tag in your master page is set to runat='server'.

David McEwing
A: 

In your initial question (before it was edited) I think you mentioned "global settings". Depending on what you want to do, you may want to look into the BasePage concept as well, since I think it might be more suitable. Since you derive from it, all its members are accessible in your code-behind.

cdonner