如何从嵌套页面中访问顶级母版页子?

How to access a top level master page sub from within a nested page?

主页结构

TOP MASTER
    PAGE MASTER "TopMaster.ErrorMsg(ErrMsg) Here throws NO error"
        PAGE "TopMaster.ErrorMsg(ErrMsg) Here throws error"

我无法从基本页面访问顶级 class。

顶级 ASPX 大师

<asp:Literal ID="litMsg" runat="Server"/>

PAGE.VB

Partial Public Class BasePage
  Inherits System.Web.UI.Page

  Public Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    TopMaster.ErrorMsg(ErrMsg) 
    "Error BC30451: TopMaster is not declared it may be inaccessible due to its protection level."
  End Sub

End Class

MASTER.VB

Partial Public Class PageMaster
  Inherits System.Web.UI.MasterPage

End Class

顶部MASTER.VB

Partial Public Class TopMaster
  Inherits System.Web.UI.MasterPage

  Public Shared Sub ErrorMsg(ErrMsg As String)
    Dim myPage = TryCast(HttpContext.Current.Handler, Page)

    If myPage IsNot Nothing Then
      Dim master = myPage.Master
      Dim myMaster = TryCast(master.Master, TopMaster)
      While master.Master IsNot Nothing AndAlso myMaster Is Nothing
        master = master.Master
        myMaster = TryCast(master, TopMaster)
      End While

      myMaster.litMsg.Text = ErrMsg
    End If

  End Sub

End Class

更新:现在清楚了,把class设为Public,不然访问不了:

Partial Public Class TopMaster

您应该向我们展示确切的错误消息,包括堆栈跟踪。似乎没有声明类型 Top Master 这没有意义,因为你在 class TopMaster.

所以我怀疑以下内容能否解决您的核心问题"Error: Top Master is not declared",但无论如何它都可能有用。

如果您想访问该文字,您应该在 TopMaster 中提供一个 属性,如下所示:

Public Property ErrorMsg As String
    Get
        Return Me.litMsg.Text
    End Get
    Set(value As String)
        Me.litMsg.Text = value
    End Set
End Property

通过这种方式,您甚至可以在不破坏代码的情况下更改控件类型。它比公开控件本身要好得多。

我猜你还必须将赋值从循环内部移到外部。你也应该在开头使用 Dim myMaster = TryCast(master, TopMaster) 而不是像使用 TryCast(master.Master, TopMaster):

那样直接跳转到页面的母版
Public Shared Sub ErrorMsg(ErrMsg As String)
    Dim myPage = TryCast(HttpContext.Current.Handler, Page)

    If myPage IsNot Nothing Then
        Dim master = myPage.Master
        Dim myMaster = TryCast(master, TopMaster)
        While master.Master IsNot Nothing AndAlso myMaster Is Nothing
            master = master.Master
            myMaster = TryCast(master, TopMaster)
        End While
        myMaster.ErrorMsg = ErrMsg
    End If

End Sub

否则,如果母版是页面的母版的母版的母版,或者它的嵌套更深,您只会分配 ErrorMsg