Thursday, August 21, 2008

Quick Tip: Getting at the current Page from MasterPage code-behind

I had to work this out today as I wanted to disable functionality on a master page based on the type of page it was attached to.

The MasterPage class is one that sits “beside” the Page class in ASP.Net – specifically, whilst you can access the MasterPage instance from a Page instance, there’s no property on the MasterPage to go back to the current page.

Of course, we can fix this with a helper class – here I’ve coded the sample as an extension method just for fun:

public static class MasterPageExtensions
{
public static Page OwningPage(this MasterPage master)
{
HttpContext context = HttpContext.Current;
Page page = context.Handler as Page;
return Page;
}
}

Now we call access the page from the code-behind of a master page thus:

public partial class MyMasterPage : MasterPage
{
private void DoSomething()
{
Page currentPage = this.OwningPage();
...
}
}

Easy!

No comments: