开发者

How to get the HTML code of ASP.NET controls, so to use that code further

开发者 https://www.devze.com 2023-01-13 07:02 出处:网络
I have made an ASP.NET table which on runtime gets populated with labels, literals, data, formatting 开发者_高级运维etc.

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 &lt;span style=&quot;color:Red;&quot;&gt;This is sample text&lt;/span&gt; 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.

0

精彩评论

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