OdeToCode IC Logo

MasterType in ASP.NET 2.0

Saturday, July 16, 2005

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
            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
        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.