asp.netplaintextrendercontrol

Rendering web controls as plain text into a string


Is there any way to render the text as it is displayed on the browser instead of the underlying html. I am trying to emulate the javascript's .innerText() functionality on the server side code.

For instance for the following code is it possible to render "Hello World" instead of

<div id="Panel1">
    <div>Hello World</div>
</div>

Here is the code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RenderControl.aspx.cs" 

Inherits="AccessibleMenu.RenderControl" Trace="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Panel ID="Panel1" runat="server">
            <div>Hello World</div>
        </asp:Panel>
    </form>
</body>
</html>
<script type="text/C#" runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        System.IO.StringWriter sw = new System.IO.StringWriter(sb);
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        Panel1.RenderControl(htw);
        Trace.Write(sb.ToString());
    }
</script>

Solution

  • When markup is not needed then PlaceHolder and Literal are your friends :)

     <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RenderControl.aspx.cs" Inherits="AccessibleMenu.RenderControl" Trace="true" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server">
                <asp:Literal ID="Literal1" runat="server" Text="Literal1"></asp:Literal>
            </asp:PlaceHolder>
        </div>
        </form>
    </body>
    </html>
    <script type="text/C#" runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.IO.StringWriter sw = new System.IO.StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            PlaceHolder1.RenderControl(htw);
            Trace.Write(sb.ToString());
        }
    </script>