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.

EC Friday, September 2, 2005
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.
Rob Gaudet Tuesday, May 30, 2006
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.
Scott Tuesday, May 30, 2006

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.
Pini Usha Monday, January 15, 2007
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?

Comments are closed.