8

I have a template for Html page, and I need to add its contents dynamically in ASP.NET. I also need to make many instences of template page, depending in data.

Its obvious that creating large Html using strings is very dirty way. So I choosed to generate my Html using HtmlGenericControl. And i made it. But I cant get the generated Html as string from it.

Its simple to add these controls in ASP.NET pages and get rendered, but I need their Html.

If its not possible, is there any other structrued way of generating Html...???

umair.ali
  • 2,714
  • 2
  • 20
  • 30
  • 1
    This one is for usercontrol, but could it help in your case ? :http://stackoverflow.com/questions/288409/how-do-i-get-the-html-output-of-a-usercontrol-in-net-c – Laurent S. May 08 '13 at 13:56

2 Answers2

22

Trick told by @Bartdude worked like a charm...

For other peoples, solution goes in this way...

// create you generic controls
HtmlGenericControl mainDiv = new HtmlGenericControl("div");
// setting required attributes and properties
// adding more generic controls to it
// finally, get the html when its ready
StringBuilder generatedHtml = new StringBuilder();
using (var htmlStringWriter = new StringWriter(generatedHtml))
{
    using(var htmlTextWriter = new HtmlTextWriter(htmlStringWriter))
    {
        mainDiv.RenderControl(htmlTextWriter);
        output = generatedHtml.ToString();       
    }
}

Hope this helps for coming readers...:)

Rudolf Dvoracek
  • 904
  • 2
  • 14
  • 30
umair.ali
  • 2,714
  • 2
  • 20
  • 30
2

And here is the same code in VB:

    Dim generatedHtml As New StringBuilder()
    Dim htw As New HtmlTextWriter(New IO.StringWriter(generatedHtml))
    mainDiv.RenderControl(htw)
    Dim output As String = generatedHtml.ToString()
Michael Dark
  • 149
  • 1
  • 5