Monday, December 13, 2010

How to Set MasterPage Variables from Content Page

Need to send information from your content page to your master page?
Despite what you may have read on a couple blogs, IT CAN BE DONE!
Here's how.

Suppose I have a variable in my code behind my master page that I want to set based on what content page is opened. In my particular case, I'm going to use an example of a menu that I will only show while browsing certain pages in my website.

The first thing I need to do is create a variable within my master page:
Private _showMenu As Boolean = False

I can use this variable later within my master page's Me.Load function to set the menu control to visible or not. Now, I need a way to interact with the Master page for this variable, so I will make a simple Property for the page:
Public Property ShowMenu() As Boolean
Get
Return _showMenu
End Get
Set(ByVal value As Boolean)
_showMenu = value
End Set
End Property


We are now done with the MasterPage, which for my example I have named "MyAwesomeMasterPage". Moving on to content pages, for each page I want to communicate with my master page, all I have to do is add one easy line in the initialization of the page. I do it so early, just in case I need to access the variable early in my master page's loading.
Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
CType(Master, MyAwesomeMasterPage).ShowMenu = True
End Sub


By casting my content page's masterpage as the MyAwesomeMasterPage page that I created, it is now aware of the Public Property that I created for it.

0 comments:

Post a Comment