如何在textareafor中解码html代码?

时间:2013-07-23 11:50:57

标签: html asp.net-mvc

我编写了以下代码来接受html标记作为模型中的数据

 [AllowHtml]
 [Required(ErrorMessage = "Post Content Required")]
 public string PostContent { get; set; }

它接受它,但是当我回调数据时,它会显示带有html标签的数据,如:

<h2><strong>&lt;p&gt;&amp;lt;p&amp;gt;[...] store and many other 
&amp;amp;hellip;&amp;lt;/p&amp;gt;&lt;/p&gt;</strong></h2>

我曾尝试撰写@HttpUtility.HtmlDecode(item.PageContent),但不删除代码..

2 个答案:

答案 0 :(得分:0)

使用@ Html.Raw输出原始HTML代码。但是,这可能会使您的网站遭受脚本攻击,因此请谨慎使用。

答案 1 :(得分:0)

由于你已经在字段上允许html,我只需将ascii转换为html,然后再将其发送到视图。

之类的东西
public string Decode(string value)
    {
        return (value)
            .Replace("&quot;", "\"")
            .Replace("&lt;", "<")
            .Replace("&gt;", ">");
    }

    public string Encode(string value)
    {
        return (value)
          .Replace("\"", "&quot;")
          .Replace("'", "''")
          .Replace("<", "&lt;")
          .Replace(">", "&gt;");
    }

然后您可以在保存到数据库之前再次对其进行编码。希望这有助于