【问题标题】:Access control in masterpage from shared function of same masterpage来自同一母版页的共享功能的母版页中的访问控制
【发布时间】:2013-02-26 11:27:12
【问题描述】:

我正在从内容页面调用母版页的共享功能。在该共享功能中,我想访问母版页中的控件,但我不知道如何。

ma​​in.master

<asp:Literal ID="ltCurrency" runat="server" />

ma​​in.master.vb

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

Public Property CurrencyText() As String
    Get
        Return ltCurrency.Text
    End Get
    Set(ByVal value As String)
        If value <> "" Then
            ltCurrency.Text = value
        End If
    End Set
End Property

Public Shared Function DoSomething() As String  
    ltCurrency.Text="SOME TEXT" 'throws error: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.    

    CurrencyText="SOME TEXT" 'this property isn't found at all

'我还尝试实例化当前母版页的一个新类: Ctype(main,Masterpage).CurrencyText

End Function


End Class

我从 page1.aspx 调用:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    main.DoSomething()
End Sub

我还能做什么?

【问题讨论】:

    标签: vb.net master-pages


    【解决方案1】:

    为了它的价值(我不知道你为什么需要让它共享),你可以使用HttpContext 来获取对你的页面的引用,并从那里得到你的主人:

    Public Shared Function DoSomething() As String
        Dim myPage = TryCast(HttpContext.Current.Handler, Page)
        If myPage IsNot Nothing Then
            Dim myMaster As main = TryCast(myPage.Master, main)
            If myMaster IsNot Nothing Then
                myMaster.ltCurrency.Text = "SOME TEXT" 
                myMaster.CurrencyText = "SOME TEXT"
            End If
        End If
    End Function
    

    【讨论】:

    • 我认为我需要共享功能才能从我的常规内容页面调用它?如果我删除“共享”部分,我将无法从内容页面使用该功能。但是您的解决方案有效:)
    • @Floran:如果你想从内容页面调用方法,你需要将页面的Master属性转换为你的MasterPage的实际类型。看看我的代码,因为我已经这样做了。
    • 啊,我明白了。但是,当我将其声明为共享方法时,我可以通过母版页类名直接访问该方法,而无需先将其转换为母版页。这里有最佳做法吗?
    • @Floran:最佳实践是使其成为实例方法,因为Shared 错误地暗示该方法也可以在没有 Http-Context 的情况下使用,实际上它访问仅在使用此母版的页面生命周期。
    • @Floran:为什么需要从内容页面调用该方法?你也可以在 master 中处理 Page_Load 并从那里调用它。
    【解决方案2】:

    第 1 步:在您的内容页面中创建一个事件。

    Public Event DoSomething(sender as object, myString as String)
    

    第 2 步:在您的主页上为您刚刚在内容页面中创建的事件添加一个事件处理程序。

    Addhandler contentPage.DoSomething, AddressOf ChangeCurrentText
    

    Step3:在处理程序中做任何你想做的事情。

    Private Sub ChangeCurrentText(sender, text)
    ltCurrency.Text = text
    End Sub
    

    Step4:在内容页面中引发事件

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        RaiseEvent DoSomething(ME, "BLAH BLAH")
    End Sub
    

    【讨论】:

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