Skip to content

Instantly share code, notes, and snippets.

@benhinman
Created December 4, 2016 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benhinman/0af79bd64b16ebc366e10ff0ccd159d0 to your computer and use it in GitHub Desktop.
Save benhinman/0af79bd64b16ebc366e10ff0ccd159d0 to your computer and use it in GitHub Desktop.
This gist allows you to get a master page of a given type from a page. It loops through all parent master pages until the given type has been found.
using System.Web.UI;
namespace Extensions
{
/// <summary>
/// Provides <see cref="Page"/> extensions.
/// </summary>
public static class PageExtensions
{
#region Methods
/// <summary>
/// Gets a master page.
/// </summary>
/// <typeparam name="T">The type of the master page.</typeparam>
/// <param name="page">The page.</param>
/// <returns>A master page.</returns>
public static T GetMasterPage<T>(this Page page) where T : MasterPage
{
T masterPage = null;
MasterPage currentMasterPage = page.Master;
while (masterPage == null && currentMasterPage != null)
{
if (currentMasterPage is T)
{
masterPage = (T)currentMasterPage;
}
currentMasterPage = currentMasterPage.Master;
}
return masterPage;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment