将Web控件作为纯文本呈现为字符串

时间:2014-02-28 15:44:30

标签: asp.net plaintext rendercontrol

有没有办法渲染文本,因为它显示在浏览器上而不是底层的html上。我试图模仿服务器端代码上的javascript的.innerText()功能。

例如,对于以下代码,可以渲染“Hello World”而不是

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

以下是代码:

<%@ 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>

2 个答案:

答案 0 :(得分:1)

您必须将HTML更改为使用文字:

<body>
    <form id="form1" runat="server">
         <asp:Literal   ID="HelloWorld" runat="server"></asp:Literal>
    </form>
</body>

你的C#:

protected void Page_Load(object sender, EventArgs e)
{
  HelloWorld.Text = 'Your text without HTML':
}

答案 1 :(得分:0)

当不需要加价时,PlaceHolder和Literal是你的朋友:)

 <%@ 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>