【问题标题】:Find exact ASP.NET Type of page from inside a Master page从母版页中查找准确的 ASP.NET 页面类型
【发布时间】:2010-01-07 23:43:01
【问题描述】:

我正在尝试从 MasterPage 中检索页面类上的自定义属性集。通常要做到这一点,我需要直接反映特定的类,但在母版页中,它总是被称为Page 类型(父类)。

如何确定Page属性的具体类型?

这是我尝试做的一个例子:

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

但它只返回附加到实际 Page 类的属性。

如果可以避免的话,我宁愿不必从 Page 派生新的基类型。

这是我的类的定义方式(在代码隐藏中):

<MyCustom()> _
Partial Class PageClass

我是不是在错误的地方定义了这个?

【问题讨论】:

    标签: .net asp.net vb.net reflection asp.net-2.0


    【解决方案1】:

    虽然Page 是实际类型,但它是一个代表 ASPX 页面的类,而不是我的属性所附加到的部分类。要找到部分类,我只需要执行以下操作:

    Page.GetType().BaseType
    

    并在上面使用了我的属性查找代码。

    感谢 TonyB 和 this SO question 为我指明了正确的方向。

    【讨论】:

      【解决方案2】:

      我认为您将错误的类型传递给 GetCustomAttributes

      我在母版页中添加了一个名为“lblMP”的标签,当我运行它时:

          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);
              }
          }
      

      它正确显示了添加到 Default.aspx 的自定义属性。这是显示我的“MPTesting.CustomAttribute”属性的输出。

      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
      

      【讨论】:

      • 执行此操作时,我的自定义属性未显示。你在哪里设置自定义属性?我已经更新了我的问题以反映这一点。
      【解决方案3】:

      您需要将页面实例传递给母版页。我可能会从页面类中将某种回调函数传递给母版页。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多