将字符串转换为 HTML 以通过 WebMethod 注入段落

Convert string to HTML to inject to paragraph via WebMethod

我正在做一个维护页面,人们可以在其中存储资源文件中将要说的内容的描述,此时在要求中他们甚至不知道文本是纯文本还是会有像 <a></a>。所以在这一点上我不得不假设情况会是这样。

本项目是在VS2010的Webforms framework 3.5中制作的。

为简单起见,我将揭示相关部分:

<article>
    <img alt="an image" src="Images/logo.jpg"/>
    <h2>Site under Maintenance</h2>
    <div>
        <p id="Description"></p>
    </div>
</article>

<script src="Includes/jquery-1.12.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "MaintenanceSite.aspx/GetMaintenanceDescription",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                $("#Description").text(msg.d);
            }
        });
    });
</script>

后端:

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetMaintenanceDescription()
{
    string mensaje = HttpUtility.HtmlEncode(Resources.MaintenanceDescription);
    return mensaje;
}

问题是,我在我的段落中收到了这个:

&lt;To href=&quot;&quot;&gt;Contact Us&lt;/a&gt;

(没有空格,因为堆栈溢出正在正确解析 html)。

我错过了什么?

这里有两个问题。首先,您需要将 C# 逻辑中对 HtmlEncode() 的调用移除为 return 纯 HTML 字符串。其次,您需要使用 jQuery 的 html() 方法来显示它而不是 text(),因为后者将再次对 HTML 进行编码。

string mensaje = Resources.MaintenanceDescription;
$("#Description").html(msg.d);