views:

242

answers:

5

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

A: 

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.

Cheeso
I assume he means in server-side code.
SLaks
I was talking about server-side, but I'm still curious what you mean. An .ascx file doesn't have a URL, right? I mean, ASPX pages do, but ASCX files don't, right?
JamesBrownIsDead
A: 

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.

Paul Hooper
+4  A: 

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.

womp
+1  A: 

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(); 
ob
A: 

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
Jakkwylde