如何从母版页读取页面变量

时间:2014-05-19 10:11:41

标签: asp.net vb.net variables global-variables master-pages

如果为每个单独的页面分配了唯一变量;在这种情况下PageID

如何在加载时从主页引用PageID

PAGE VB

Partial Class Index
  Inherits System.Web.UI.Page

  Dim PageID As Integer = 1
End Class

MASTER VB

Partial Class MasterPage
  Inherits System.Web.UI.MasterPage

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If PageID = 1 Then
    ...
    End If
  End Sub
End Class

我知道这可以通过查询字符串来实现,但是由于潜在的页面数量,我正在寻找更有效和更安全的解决方案。

1 个答案:

答案 0 :(得分:1)

公开一个返回该字段的公共属性,然后你只需要将Page中的MasterPage属性转换为具体类型:

Dim index As Index = TryCast(Me.Page, Index)
If index IsNot Nothing Then
    Dim pageID As Int32 = index.PageID
End If

Index课程中:

Partial Class Index
    Inherits System.Web.UI.Page

    Private _PageID As Integer = 1
    Public Property PageID As Int32
        Get
            Return _PageID
        End Get
        Set(value As Int32)
            _PageID = value
        End Set
    End Property

End Class

由于您希望在每个页面中都需要定义界面。您可以让他们实现相同的Interface,例如IPageable

Public Interface IPagable
    Property PageID As Int32
End Interface

现在让所有页面实现它:

Partial Class Index
    Inherits System.Web.UI.Page
    Implements IPagable

    Private _PageID As Integer = 1
    Public Property PageID As Int32 Implements IPagable.PageID
        Get
            Return _PageID
        End Get
        Set(value As Int32)
            _PageID = value
        End Set
    End Property

End Class

并相应地更改MasterPage:

Dim pageable As IPagable = TryCast(Me.Page, IPagable)
If pageable IsNot Nothing Then
    Dim pageID As Int32 = pageable.PageID
End If