我有一个常见的用户控件,比如TextBoxUserControl.ascx,它用于三个不同的页面,比如A.aspx,B.aspx和C.aspx。
A.aspx有一个隐藏的控件,比如,hiddenA
B.aspx有一个隐藏的控件,比如,hiddenB
C.aspx有一个隐藏的控件,比如hiddenCxyz
当从不同页面加载TextBoxUserControl.ascx时,我想从TextBoxUserControl.ascx中读取父页面的隐藏值。
但是,我面临的问题是不如何在TextBoxUserControl.ascx的Page_Load中显式编码隐藏字段名称?如何在它们之间分离?
下面是TextBoxUserControl.ascx的Page_Load方法
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
' below hiddenA of A.aspx is explicitly being checked, but it wont work if this user control
' is used in B.aspx and C.aspx as they have different names of hidden fields
Control ctr = Me.Parent.FindControl(hiddenA)
labelTotal = ctr.Text
End Sub
答案 0 :(得分:1)
我实现这一点的方法是为托管页面创建一个返回适当值的接口(甚至不用担心控件)。
例如:
Public Interface IPageHost
ReadOnly Property PageNameGuid As String
End Interface
然后,在a.aspx中实现此接口:
Public Class APage
Inherits System.Web.UI.Page
Implements IPageGuidHost
Public ReadOnly Property PageNameGuid As String Implements IPageGuidHost.PageNameGuid
Get
Return hiddenA.Text
End Get
End Property
最后,在用户控件中,如果父页面实现了接口,只需直接获取值:
Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim parentPage As IPageGuidHost
parentPage = TryCast(Me.Page, IPageGuidHost)
If parentPage IsNot Nothing Then
labelTotal.Text = parentPage.PageNameGuid
Else
lableTotal.Text = String.Empty
End If
End Sub