OdeToCode IC Logo

Page Inheritance in ASP.NET 2.0

Monday, September 12, 2005

Rick Strahl has a fantastic post: “Understanding Page Inheritance In ASP.NET 2.0”. Go read the post now.

Here are some ideas I thought of while reading.

The @ Reference, @ MasterType and @ PreviousPage directives are the only reliable mechanisms for referencing a type defined in another page (or user control, or master page) from inside a web form.

In Rick’s case he wanted to create a new web form (UploadItemPictureEx) derived from UploadItemPicture, where UploadItemPicture is defined as a Page derived class in the CodeFile for a second web form. In the new compilation model UploadItemPicture isn’t visible from the code inside the UploadItemPictureEx web form. This behavior is dramatically different from 1.1, as Rick clearly explains.

One solution is to define a base class for both web forms and stick the class in App_Code or a class library. Another solution is to use @ Reference, e.g:


If you place the above in UploadItemPictureEx.aspx, you’ll be able to use the UploadItemPicture type inside the CodeFile without any hassle.

The @ MasterType directive is useful when you want a strongly typed Master property for your page. I described @ MasterType in a previous post.

Likewise, the @ PreviousPage directive is useful during Server.Transfer and cross page postbacks. The runtime will give you a strongly typed PreviousPage property. I have some example of using @ PreviousPage in this article.

If you are dynamically loading user controls with LoadControl and don’t know which control you need to @ Register or @ Reference, I don’t see any choice but to define a base class for the control and keep the class in App_Code or in a class library referenced by the web project.