How to get the generated HTML form HtmlGenericControl

I have a template for an HTML page, and I need to dynamically add its contents to ASP.NET. I also need to do many instances of the template, depending on the data.

Obviously creating large Html using strings is very messy. So I decided to generate my Html using HtmlGenericControl. And I did it. But I can not get the generated Html as a string from it .

Its easy to add these controls to ASP.NET pages and get renderings, but I need their Html.

If this is not possible, is there another structured way to generate Html ... ???

+6
source share
2 answers

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

For other nations, the solution goes 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 visitors coming ... :)

+20
source

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() 
+1
source

Source: https://habr.com/ru/post/944529/


All Articles