17

Hi I want to call the corresponding html inside a Panel in code behind. How can I do that?

I have this

<asp:Panel ID="MyPanel" runat="server">
    // other asp.net controls and html stuffs here.
</asp:Panel>

I want to get the HTML equivalent of MyPanel and all of its contents in my code behind say in PageLoad or some methods.

Thanks.

rob waminal
  • 18,117
  • 17
  • 50
  • 64
  • Similar question here: http://stackoverflow.com/questions/58925/asp-net-how-to-render-a-control-to-html – Tillito Mar 13 '15 at 20:54

2 Answers2

36

Does RenderControl() not work?

Create an instance of your control and then call RenderControl() on it. Of course this implies that your panel is in a UserControl

example from comments:

StringBuilder sb = new StringBuilder(); 
StringWriter tw = new StringWriter(sb); 
HtmlTextWriter hw = new HtmlTextWriter(tw); 
ctrl.RenderControl(hw); 
var html = sb.ToString(); 
TheAlbear
  • 5,507
  • 8
  • 51
  • 84
Shiv Kumar
  • 9,599
  • 2
  • 36
  • 38
  • but the return type of RenderControl() is void.. I need to get the HTML equivalent as a string or an object. – rob waminal Nov 12 '10 at 06:25
  • 1
    You pass in a TextWriter to the RenderControl() method. When the method returns, you have your html in the TextWriter – Shiv Kumar Nov 12 '10 at 06:29
  • 12
    StringBuilder sb = new StringBuilder(); StringWriter tw = new StringWriter(sb); HtmlTextWriter hw = new HtmlTextWriter(tw); ctrl.RenderControl(hw); var html = sb.ToString(); – Shiv Kumar Nov 12 '10 at 06:31
  • Where ctrl is the instance of your UserControl – Shiv Kumar Nov 12 '10 at 06:32
  • What if I don't want my control to appear on the page (i.e. not visible) – avivas Feb 03 '12 at 21:38
  • The StringWriter default constructor creates a new string builder. Example could be simplified to- StringWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); ctrl.RenderControl(hw); var html = tw.ToString(); – Spongeboy Apr 09 '14 at 00:54
  • This always gave me an empty string. However, a7drew's solution here worked like charme: http://stackoverflow.com/questions/58925/asp-net-how-to-render-a-control-to-html (I was calling via web service, maybe that was the reason why this solution did not work?) – Tillito Mar 13 '15 at 20:54
  • This is helping me b/c I'm receiving the must be in webform error, if your asp.net control contains any button controls, etc: http://www.4guysfromrolla.com/articles/122006-1.aspx – Nathan Prather Nov 07 '16 at 22:58
  • 1
    This doesn't work if (for example) an element like a
    was added to the panel dynamically via javascript. The dynamically added content doesn't appear in the result.
    – Snailer Jul 14 '17 at 07:05
3

@Shiv Kumar's answer is correct. However you don't need the StringBuilder for this.

StringWriter tw = new StringWriter(); 
HtmlTextWriter hw = new HtmlTextWriter(tw); 
ctrl.RenderControl(hw); 
var html = tw.ToString();

This also works

Beingnin
  • 2,288
  • 1
  • 21
  • 37