18

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.

1

2 Answers 2

37

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(); 
Sign up to request clarification or add additional context in comments.

9 Comments

but the return type of RenderControl() is void.. I need to get the HTML equivalent as a string or an object.
You pass in a TextWriter to the RenderControl() method. When the method returns, you have your html in the TextWriter
StringBuilder sb = new StringBuilder(); StringWriter tw = new StringWriter(sb); HtmlTextWriter hw = new HtmlTextWriter(tw); ctrl.RenderControl(hw); var html = sb.ToString();
Where ctrl is the instance of your UserControl
This doesn't work if (for example) an element like a <div> was added to the panel dynamically via javascript. The dynamically added content doesn't appear in the result.
|
4

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.