c# - 为什么 JSON 响应中的 HTML 会被编码?

标签 c# jquery json asp.net-mvc-2 jtemplate

我正在使用this blog post as a guide ,详细介绍了如何使用 jQuery 和 jTemplates 将 JSON 响应填充到模板中。

我的问题是,返回的字段之一(名为“描述”)包含 HTML,但 HTML 括号被编码为\u003C 和\u003e。

这是服务器返回的 HTML(在描述字段中):

<a href="/en/Yokota/User/Show/Chad">Chad</a> updated their ad, <a href="/en/Yokota/Ad/Show/100">Validation Test Ad Again</a>, @<a href="/en/Yokota">Yokota</a>

JSON 响应如下所示:

[{"TypeOfActivity":"0","Description":"\u003ca href=\"/en/Yokota/User/Show/YokotaTour\"\u003eYokotaTour\u003c/a\u003e posted \u003ca href=\"/en/Yokota/Ad/Show/166\"\u003eOne of the best for sure\u003c/a\u003e for sale @\u003ca href=\"/en/Yokota\"\u003eYokota\u003c/a\u003e","DateHappened":"6/23/2010 12:26:55 AM"}]

注意“\u003c”或“\u003e”。这些看起来像是 unicode 转义,但为什么会发生这种情况呢?这是调用 JSON 响应的 jQuery:

$.getJSON("<%= Url.Action("List", "Activity") %>",
    function(data){
        $("#aLog").setTemplate($("#templateHolder").html());
        $("#aLog").processTemplate(data);
    });

更新

这就是页面加载完成后源代码的样子(在 Firefox 中查看 > 页面源代码):

&lt;a href="/en/Yokota/User/Show/Chad"&gt;Chad&lt;/a&gt; updated their ad, &lt;a href="/en/Yokota/Ad/Show/100"&gt;Validation Test Ad Again&lt;/a&gt;, @&lt;a href="/en/Yokota"&gt;Yokota&lt;/a&gt;

也许是因为时间已接近凌晨 3 点,但我很困惑......非常感谢任何帮助 - 谢谢!

更新2

public JsonResult List()
{
    IList<ActivityContract> contracts = new List<ActivityContract>();
    var activityList = _db.Activity.ByBaseID(CurrentBase.BaseID).OrderByDescending(a => a.DateHappened);
    foreach (var a in activityList) {
        contracts.Add(new ActivityContract { TypeOfActivity = a.TypeOfActivity.ToString(), Description = a.Description, DateHappened = a.DateHappened.ToString() });
    }
    return Json(contracts, JsonRequestBehavior.AllowGet);
}

最佳答案

事实证明,问题出在 jTemplates 中的设置上。 setTemplate 行需要是这样的:

$("#aLog").setTemplate($("#templateHolder").html(), [], {filter_data: false});

特别是,filter_data 必须设置为 false。默认情况下 jTemplates html 编码。 ;(

关于c# - 为什么 JSON 响应中的 HTML 会被编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3095621/

相关文章:

c# - Monitor.PulseAll() 中需要帮助

c# - 使用 Kendo Grid,如何更改工具栏中 "Create"按钮上的文字?

javascript - 来自响应的数据是无法设置为 iframe 的符号

javascript - 转换对象js显示

php - php中的json对象没有被读取

c# - HttpStatusCodeResult(401) 返回 "302 Found"

c# - 使用相同的 HttpWebRequest obj 请求第二个 url

c# - 在 DropDownListFor 上添加搜索功能

jquery - 自动完成建议列表错误的 z-index,我该如何更改?

json - 检索 JSON 数据然后解析它(需要一些帮助)