我正在构建一个应用程序,其中页面将根据查询字符串动态加载用户控件(x.ascx)。

我在页面上有验证摘要,并希望从用户控件更新它。这将允许我使用一个验证摘要进行多个控制。如何在控件和页面之间传递数据。

我知道我可以在设计时定义控件并使用事件来执行此操作,但这些控件是使用Page.LoadControl动态加载的。

另外,我想避免使用会话或查询字符串。

有帮助吗?

解决方案

找到了一种方法:

步骤1:创建基本用户控件并在此控件中定义代理和事件。

步骤2:在基本用户控件中创建一个公共函数,以提高在步骤1中定义的事件。

'SourceCode for Step 1 and Step 2
Public Delegate Sub UpdatePageHeaderHandler(ByVal PageHeading As String)
Public Class CommonUserControl
    Inherits System.Web.UI.UserControl

    Public Event UpdatePageHeaderEvent As UpdatePageHeaderHandler
    Public Sub UpdatePageHeader(ByVal PageHeadinga As String)
        RaiseEvent UpdatePageHeaderEvent(PageHeadinga)
    End Sub
End Class

步骤3:从您在Step1中创建的基本用户控件继承Web用户控件。

步骤4:从Web用户控件 - 调用您在Step2中定义的MyBase.FunctionName。

'SourceCode for Step 3 and Step 4
Partial Class DerievedUserControl
    Inherits CommonUserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        MyBase.PageHeader("Test Header")
    End Sub
End Class

步骤5:在您的页面中,使用Page.LoadControl动态加载控件并将控件转换为基本用户控件。

步骤6:使用此控件附加事件处理程序。

'SourceCode for Step 5 and Step 6
Private Sub LoadDynamicControl()
    Try
        'Try to load control
        Dim c As CommonUserControl = CType(LoadControl("/Common/Controls/Test.ascx", CommonUserControl))
        'Attach Event Handlers to the LoadedControl
        AddHandler c.UpdatePageHeaderEvent, AddressOf PageHeaders
        DynamicControlPlaceHolder.Controls.Add(c)
    Catch ex As Exception
        'Log Error
    End Try
End Sub

其他提示

假设您正在讨论asp的验证器控件,那么使它们与验证摘要一起使用应该很简单:使用相同的验证组。通常,我从基类派生所有usercontrols,该基类添加ValidationGroup属性,其setter调用overriden方法,该方法将所有内部验证器更改为同一验证组。

棘手的部分是让它们在动态添加时表现出来。您应该注意一些问题,主要是关于页面循环以及何时将它们添加到Page对象中。如果您知道在设计时使用的所有可能的用户控件,我会尝试使用EnableViewState和Visible静态添加它们,以最大限度地减少开销,即使它们太多也是如此。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top