Friday, April 24, 2015

ASP.Net C# Accessing a BasePage from a Master page

In most of my designs there is at minimum a Master page, and several Content pages that use the Master page and inherit from a BasePage.

In some circumstances there might be properties or methods in the BasePage that you want to access from the Master page code-behind.

BasePage.cs
   public class BasePage : System.Web.UI.Page  
   {  
   }  

Base.Master
     private BasePage MyBasePage  
     {  
       get  
       {  
         try  
         {  
           return (BasePage)Page;  
         }  
         catch  
         {  
           return new BasePage();  
         }  
       }  
     }  

Now you can use the MyBasePage variable to access any public information in the BasePage class.

Of course the try/catch is in there to handle situations where a content page may not actually inherit from the BasePage, in which case that would throw an error. That could be handled a few different ways, but that's partly dependent on how you plan to use it. In most cases all of my content pages inherit from the BasePage and this is a safe solution.

This same technique also works if you need to access the BasePage from within a user control.

Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey

2 comments: