ASP.NET: Getting markup for .ascx

时光毁灭记忆、已成空白 提交于 2019-12-24 07:08:09

问题


Let's say I have an a .ascx user control. How do I get its HTML markup into a string?


回答1:


Once you use the LoadControl() method to get it into a page, you can can get the HTML by calling the Render() method on it. It requires an HtmlTextWriter to write to, but it's fairly straightforward to construct:

var userControl = (userControlType)Page.LoadControl( ....ascx);
StringBuilder sb = new StringBuilder();
StringWriter SW = new StringWriter(SB);
HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
userControl.RenderControl(htw);

string html = sb.ToString();

If you're not inside the page context, there are other ways to do it.




回答2:


i haven't verified the code, but in theory if you have a reference to your UserControl you should be able to call Render()

StringBuilder sb = new StringBuilder();
using (StringWriter tw = new StringWriter(sb))
using (HtmlTextWriter hw = new HtmlTextWriter(tw))
{
    ctrl.Render(hw);
}
return sb.ToString(); 



回答3:


You don't explain what you mean by "get its HTML".

If you are talking about a web client, then the way to get the markup is to send an HTTP GET to the URL.




回答4:


The HTML for a UserControl is generally not created until the Render() method of the UserControl is called. That method generates the HTML and sends the content to the HtmlTextWriter.

Check out documentation on UserControl.Render() for more info.




回答5:


Give this a try, works like a champ for grabbing the generated markup from a user control

    Dim controlText As String = String.Empty
    controlText = Me.GenerateControlMarkup("/SampleUserControl/Grid.ascx")

Public Class SacrificialMarkupPage
    Inherits Page
    Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    End Sub
End Class

Private Function GenerateControlMarkup(ByVal virtualPath As String) As [String]
    Dim page As New SacrificialMarkupPage()
    Dim ctl As UserControl = DirectCast(page.LoadControl(virtualPath), UserControl)
    page.Controls.Add(ctl)
    Dim sb As New StringBuilder()
    Dim writer As New StringWriter(sb)

    page.Server.Execute(page, writer, True)
    Return sb.ToString()
End Function


来源:https://stackoverflow.com/questions/2113567/asp-net-getting-markup-for-ascx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!