Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the HTML rendered by ASP.NET control in Code behind

Tags:

c#

asp.net

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.

like image 762
rob waminal Avatar asked Nov 12 '10 06:11

rob waminal


People also ask

How can access HTML table in ASP.NET code behind?

You have to add runat="server" tag to the HTML table and access that table by Id in Code behind. and then CAST it to HTMLTable.

What is ASP.NET code behind?

If you use code-behind class files with . aspx pages, you can separate the presentation code from the core application logic (or code-behind). The code-behind class file is compiled so that it can be created and used as an object. This allows access to its properties, its methods, and its event handlers.


2 Answers

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(); 
like image 182
Shiv Kumar Avatar answered Sep 22 '22 06:09

Shiv Kumar


@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

like image 21
Beingnin Avatar answered Sep 25 '22 06:09

Beingnin