Tuesday, January 16, 2007

Accessing Master page variables from user control

Recently , i had a task to generate meta tags depending on the list of items that are shown on each page (Pageflakes Community Gallery). The list is generated using a repeater and it is under a user control. The header tag is in the Master page, inside which i need to generate the meta tags. Within the header tag , i have <%= MetaTag %>, which dumps whatever assigned to it. MetaTag holds the string of meta tags, which is generate from a predefined schema , after doing some content processing.

Now,calling a public method in master page from user control is bit tricky.To call a public variable from a user control , the following line must be copied to the top of user control with appropiate master page location.

<%@ Reference VirtualPath="~/YourPath/youMasterPage.master" %>

This enables to take the reference of the master page codebehind class and access its public variables.

ASP.MysNameSpace_MasterPageClass myMaster = (ASP.MysNameSpace_MasterPageClass)this.Page.Master;

myMaster.MetaTag = GetMetaTag(.....);


This process of accessing public variable though simple, yet very effective way of dynamic inclusion of meta tags, scripts, style tags and even custom title on to the header tag which is under a common master page.

Ping me if you have anything to share with me.

2 comments:

Asif said...

Hi.. you article was useful. But i am getting error while adding the following line in the User Control.

Reference VirtualPath="~/MyNewMasterPage.master"

on the top of the UserControl..

Error:UserControl Has Circular Reference.

Please suggest a Solution...

Robert Huguley WorkLogs said...

Try MasterType instead of Reference