如何从嵌套页中访问顶级母版页子页
本文关键字:母版页 访问 嵌套 | 更新日期: 2023-09-27 17:54:40
主页结构
TOP MASTER
PAGE MASTER "TopMaster.ErrorMsg(ErrMsg) Here throws NO error"
PAGE "TopMaster.ErrorMsg(ErrMsg) Here throws error"
我无法从基页获得对顶级类的访问权。
TOP MASTER 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
更新:现在很清楚了,让类Public
,否则你不能访问它:
Partial Public Class TopMaster
你应该向我们展示包括stacktrace在内的准确的错误信息。似乎没有声明类型Top Master
,因为您在TopMaster
类中,这没有意义。
所以我怀疑下面修复了你的核心问题"错误:顶级大师没有声明",但它可能是有用的。
如果您想访问该文字,您应该在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
。