首页 > 解决方案 > 如何在自定义控件中呈现来自 aspx 页面的内容

问题描述

我正在编写一个复合控件,它应该呈现放置在使用 aspx 页面中它的开始和结束标记之间的任何内容。

VB

Public Class MyComposite
    Inherits CompositeControl
    Implements INamingContainer

    Public Property UserContentTemplate as ITemplate = Nothing

    Public Overrides ReadOnly Property Controls() As ControlCollection
        Get
            EnsureChildControls()
            Return MyBase.Controls
        End Get
    End Property

    Protected Overrides Sub CreateChildControls()
        ' This is where I'm creating the controls
        ' for the composite
    End Sub

    Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
        ' This is where I render the composite controls
    End Sub

    Protected Overrides Sub RecreateChildControls()
        EnsureChildControls()
    End Sub

    Public Overrides Sub DataBind()
        CreateChildControls()
        ChildControlsCreated = True
        MyBase.DataBind()
    End Sub
End Class

从这里UserContentTemplate在消费 aspx 页面中可用

<cc:MyComposite runat="server" ID="MyCompositeID">
    <UserContentTemplate>
        <asp:Button... />
        <asp:TextBox... />
    </UserContentTemplate>
</cc:MyComposite>

此时,asp:Buttonandasp:TextBox没有被渲染。我已经查看了此链接Building Templated Custom ASP.NET Serv Controls,但我不知道这是否适用或如何在我的情况下应用它。如果您查看链接,您会看到<StatsTemplate>标签内有 HTML 元素,这些元素在自定义控件中呈现。

标签: c#asp.netvb.netcustom-server-controls

解决方案


HTML of 以下函数返回呈现控件的 HTML。

您可以使用占位符来添加所有用于渲染的控件并将占位符传递给函数,或者您可以直接传递您的控件。

 Public Function RenderUserControlToString(ByRef WebControl As Control) As String

        Dim sb As StringBuilder = New StringBuilder
        Dim sw As StringWriter = New StringWriter(sb)
        Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
        Try
            WebControl.RenderControl(htw)
        Catch ex As Exception
            sb.Append(ex.Message & vbCrLf & ex.StackTrace)
        End Try
        Return sb.ToString()
    End Function

推荐阅读