views:

162

answers:

3

I'm trying to retrieve a custom Attribute set on a page's class from inside the MasterPage. Normally to do this I would need to reflect directly on the specific class, but inside the Master page it's always referred to as the Page type (the parent class).

How do I determine the specific type of the Page property?

Here's an example of what I'm trying to do:

Dim attrs() As Object = Page.GetType().GetCustomAttributes(GetType(MyCustomAttribute), False)
For Each attr As MyCustomAttribute In attrs
    ' Do something '
Next

but it only ever returns the attributes attached to the actual Page class.

I'd rather not have to derive a new base type from Page if I can avoid it.

Here is how my class is defined (in the code-behind):

<MyCustom()> _
Partial Class PageClass
Am I defining this in the wrong place?

A: 

You need to pass the page instance to the master page. I'd probably pass some kind of callback function to the master page from within the page class.

Rodrick Chapman
+1  A: 

I think you are passing the wrong type to GetCustomAttributes

I added a label called "lblMP" to my master page and when I run this:

    protected void Page_Load(object sender, EventArgs e)
    {
        lblMP.Text = this.Page.GetType().AssemblyQualifiedName;

        foreach( var a in Attribute.GetCustomAttributes(this.Page.GetType()))
        {
            lblMP.Text = String.Format("{0} <br />{1}", lblMP.Text, a);
        }
    }

It correctly shows the custom attribute added to Default.aspx. Here is the output showing my "MPTesting.CustomAttribute" attribute.

ASP.default_aspx, App_Web_tkeebnzk, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
System.Runtime.CompilerServices.CompilerGlobalScopeAttribute
MPTesting.CustomAttribute
System.ComponentModel.DesignerAttribute
System.ComponentModel.ToolboxItemAttribute
System.ComponentModel.DefaultEventAttribute
System.ComponentModel.DesignerCategoryAttribute
System.ComponentModel.Design.Serialization.DesignerSerializerAttribute
System.ComponentModel.DesignerAttribute
System.ComponentModel.Design.Serialization.DesignerSerializerAttribute
System.ComponentModel.DefaultPropertyAttribute
System.ComponentModel.BindableAttribute
System.Web.UI.ThemeableAttribute
System.Web.UI,Require
TonyB
My custom attribute does not show up when I do this. Where are you setting the custom attribute? I've updated my question to reflect this.
Andrew Koester
A: 

While Page was the actual type, it was a class representing the ASPX page rather than the partial class my attribute was attached to. To find the partial class I only had to do the following:

Page.GetType().BaseType

and used my attribute-finding code on that.

Thanks to TonyB and this SO question for pointing me in the right direction.

Andrew Koester