MasterType in ASP.NET 2.0

Here is something nice that comes from the new compilation model in ASP.NET 2.0. Let’s say you add a custom property to a master page code-behind file like so:

Partial Class otcMaster
    Inherits System.Web.UI.MasterPage

    Public Property FooterText() As String
        Get
            Return Footer.Text
        End Get
        Set(ByVal value As String)
            Footer.Text = value
        End Set
    End Property

End Class

You can get to the master page for a web form using the inherited Master property, which returns a MasterPage reference. To get to a property defined in otcMasterPage though, you might think you need to use a cast.


CType(Master, otcMaster).FooterText ="foo"

Casting to a derived type is just a part of life when using frameworks and statically typed languages, but there is a better way. Use the @ MasterType directive in the ASPX.

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

Now when ASP.NET codegens the page, it puts the following inside a partial class definition. Notice the Shadows keyword (that would be the new keyword in semicolon land [yeah, I’m experimenting with alternative languages]).

Public Shadows ReadOnly Property Master() As otc
    Get
        Return CType(MyBase.Master,otcMaster)
    End Get
End Property

The result is a strongly typed Master Page. We don’t need a cast, we can go right to the Master.FooterText property. Another way to do this is to specify a TypeName in the @MasterType directive.

Print | posted @ Saturday, July 16, 2005 6:14 AM

Comments on this entry:

Gravatar # re: MasterType in ASP.NET 2.0
by EC at 9/2/2005 6:34 PM

Sure experienced developers do not like the new ASP.NET 2.0 - It makes them lose their job!

ASP.NET 2.0 cuts work time by half and it is the future.
  
Gravatar # re: MasterType in ASP.NET 2.0
by Rob Gaudet at 5/30/2006 4:34 PM

One gotcha to watch out for when using the @ MasterType directive in the ASPX is changing the masterpage programmatically is not possible (That I have found). So you only want to use it if you are sure that you will never need to programmatically change the masterpage.
  
Gravatar # re: MasterType in ASP.NET 2.0
by Scott at 5/30/2006 6:20 PM

Rob:

You can programatically change the page, but you need to use the MasterType directive with a type name (not a virutal path), and make the type you point to a base class for your master pages.
  
Gravatar # re: MasterType in ASP.NET 2.0
by Pini Usha at 1/15/2007 12:19 PM

Hi,
All my pages inherit from BasePage who inherit from Page.
I want to use this cool feature but BasePage don't have html file its just cs file.
How can i set it to my basepage?

Thanks.
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 3 and 2 and type the answer here: