c# - 如何在自定义控件中呈现来自 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:Button
andasp:TextBox
没有被渲染。我已经查看了此链接Building Templated Custom ASP.NET Serv Controls,但我不知道这是否适用或如何在我的情况下应用它。如果您查看链接,您会看到<StatsTemplate>
标签内有 HTML 元素,这些元素在自定义控件中呈现。
解决方案
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
推荐阅读
- javascript - wix-events-backend createEvent() 代码在 eventInfo 上失败
- python - Matplotlib - 在带有负和正 y 轴的折线图中提高刻度线
- racket - 让 vs Local 在球拍中定义
- enums - 错误在哪里:在规范或代码生成中?
- java - ElementClickInterceptedException:在点 (470, 236) 处不可点击
- python - 遍历最近的图像,flickrapi
- servicestack - ServiceStack.OrmLite:处理集群中多个节点的最佳实践(多主节点)
- javascript - 我想获取所有父节点及其子节点,在 javascript 中使用给定数据的子 ID
- javascript - 当 discord.js 机器人断开连接时,我需要清除队列
- visual-studio-2019 - 如何在VS2019扩展中创建工具窗口