我将HTML存储在数据库中并尝试使用文字控件在页面上呈现它。问题是文字不是渲染代码而只是在网页上显示标记。我已经检查了HTML,它直接添加到页面时工作正常,但在设置为文字文本属性时不起作用。
之前我已经做了很多次,面对我重复使用代码但由于某种原因只显示了标记。
页面上的文字:
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentArea" Runat="Server">
<asp:Literal ID="Literal1" runat="server" Mode="PassThrough"></asp:Literal>
</asp:Content>
VB代码:
Private Sub LoadContent()
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim conn As SqlConnection = New SqlConnection
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("ConnectionString").ConnectionString
Dim cmd As SqlCommand = New SqlCommand
cmd.CommandText = ("select HTML from Pages where " & _
"PageName like @SearchText + '%'")
cmd.Parameters.AddWithValue("@SearchText", "TheShop")
cmd.Connection = conn
Dim sb As StringBuilder = New StringBuilder
conn.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
sb.Append(sdr("HTML")) _
.Append(Environment.NewLine)
End While
conn.Close()
Literal1.Text = sb.ToString
End Sub
这是sb.ToString在添加到文字之前的内容:
<p><span style="color:#FF0000">revergveraer</span></p>
<p><span style="color:#FF0000"><img alt="" src="http://pngimg.com/upload/fish_PNG1156.png" style="height:133px; width:200px" />rgergerg</span></p>
这是输出的HTML,并由文字显示为标记:
<p><span style="color:#FF0000">revergveraer</span></p> <p><span style="color:#FF0000"><img alt="" src="http://pngimg.com/upload/fish_PNG1156.png" style="height:133px; width:200px" />rgergerg</span></p>
答案 0 :(得分:4)
您的HTML已经过编码,需要先解码才能通过Literal呈现。使用Server.HtmlDecode
很容易。
Literal1.Text = Server.HtmlDecode(sb.ToString)
但是,我建议您不要像使用代码那样使用Environment.NewLine
,而是使用:
sb.append("<br/>")