开发者

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

开发者 https://www.devze.com 2023-01-25 05:59 出处:网络
Hi I want to call the corresponding开发者_如何学C html inside a Panel in code behind. How can I do that?

Hi I want to call the corresponding开发者_如何学C 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.


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(); 


@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

0

精彩评论

暂无评论...
验证码 换一张
取 消