How to get the HTML code of ASP.NET controls, so to use that code further
I have made an ASP.NET table which on runtime gets populated with labels, literals, data, formatting 开发者_高级运维etc.
form1.innerhtml says page does not have literals only.
I need to extract this ASP.NET table generated at runtime as HTML code so that it can be exported to a Word file..(as Word easily supports HTML) and the browser is also displaying HTML.
So how to get the HTML?
You can render the control into a string.
public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}
Edited: Here is a complete .aspx page. All I did is create a new website, put the following code in and hit F5.
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label lbl = new Label();
lbl.Text = "This is sample text";
lbl.ForeColor = System.Drawing.Color.Red;
string html = RenderControl(lbl);
Response.Clear();
Response.Write(HttpUtility.HtmlEncode(html));
Response.End();
}
public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}
}
The output is
<span style="color:Red;">This is sample text</span>
which the browser displays as <span style="color:Red;">This is sample text</span>
.
Note that you could also eliminate the StringBuilder, use new StringWriter();
and return tw.ToString();
. StringWriter uses a StringBuilder as its underlying data structure anyway.
Look at the HttpResponse.Filter property.
精彩评论