javascript - 如何将此 Json 数组转换为 JQuery 可读的格式?

标签 javascript jquery ajax json asp.net-mvc-3

有点模糊的问题,但我不确定如何才能做到这一点。 Firebug 说我的 ajax 请求中的 Json 对象(数组?)如下所示:

{
"jsonResult":
"[
   {\"OrderInList\":1},
   {\"OrderInList\":2}
]"
}

这是通过 $.getJSON ajax 请求检索的:

    $.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, testData, function (jsonResult) {
        $('#orderInList option').remove();

        var map = {
            "TestKey1": "TestValue1",
            "TestKey2": "TestValue2"
        };

        $.each(jsonResult, function (key, value) {
            $("#orderInList").append($("<option value=" + key + ">" + value + "</option>")
            );
        });

如果我将 $.each(jsonResult) 替换为 $.each(map),则选择列表会正确填充。否则我的选择列表只会显示“未定义”。

我在 MVC Controller 中序列化此 Action 中的 Json:

    public JsonResult GetOrderSelectList(int parentCategoryId)
    {
        var result = Session
            .QueryOver<Category>()
            .Where(x => x.Parent.Id == parentCategoryId)
            .OrderBy(x => x.OrderInList).Asc
           .List();

        var toSerialize =
            result.Select(r => new {r.OrderInList});

        var jsonResult = JsonConvert.SerializeObject(toSerialize);                             
        return Json(new
                        { jsonResult,
                        }, JsonRequestBehavior.AllowGet);

    }

所以我认为问题可能是 Action 响应的 Json 格式?任何帮助表示赞赏!

编辑答案

下面的两个答案都对我有帮助。我似乎无法强类型变量 jsonResult 所以感谢 @JBabey 指出我在读取 json 属性时的错误,并在 $.each 语句中建议函数(键,值)。

感谢@Darin Dimitrov 帮助我解决了 Controller 问题!

最佳答案

您的 Controller 操作错误。您在其中手动进行 JSON 序列化,然后将其作为 JSON 结果返回,从而最终得到双重 JSON 序列化。您可以直接返回数组,并将 JSON 序列化管道留给 ASP.NET MVC 框架:

public ActionResult GetOrderSelectList(int parentCategoryId)
{
    var result = Session
        .QueryOver<Category>()
        .Where(x => x.Parent.Id == parentCategoryId)
        .OrderBy(x => x.OrderInList)
        .Asc
        .List();
    return Json(result, JsonRequestBehavior.AllowGet);
}

然后:

$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, testData, function (jsonResult) {
    $('#orderInList option').remove();
    $.each(jsonResult, function () {
        $('#orderInList').append(
            $("<option value=" + this.Id + ">" + this.Value + "</option>")
        );
    });
});

请注意,我在这里使用了 this.Idthis.Value。假设 JSON 结果如下所示:

[{"Id": 1, "Value": "some value"}, {"Id": 2, "Value": "some other value"}]

您必须根据实际的类别模型调整这些属性名称。

关于javascript - 如何将此 Json 数组转换为 JQuery 可读的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11923298/

相关文章:

javascript - 基于 thunk 或基于配对的延迟类型的表达能力是否存在差异?

javascript - 如何使用 JavaScript 动态创建 UTF 字符

javascript - FadeSlideShow - Javascript 目标 = "_blank"

javascript - 在 JavaScript 中定义全局对象的实现独立版本

jquery - bootstrap 2.3.2 popover html 内容问题

jQuery Accordion 100% 宽度

php - php中如何在不刷新页面的情况下获取cookie?

java - 从 JavaScript (AJAX) 调用和使用 JBoss Web 服务

jquery - 如何使 AJAX 请求看起来像常规的正常请求

javascript - 在没有 Math.max() 的情况下查找一串数字中的最大值