我如何迭代json数组的数组

时间:2014-02-19 16:06:38

标签: asp.net-mvc json

我想从控制器迭代一个json数组数组我想知道如何迭代它

我需要帮助:nay可以帮助我,我是json和mvc的新手

//server code

        var jsonData = new
        {

            rows =
            (from bathymetrie in bathymetries

             select new
             {
                 count = bathymetries.Count,
                 Id = bathymetrie.Id,
                 date = (bathymetrie.displayedDate != null) ? 
        bathymetrie.displayedDate.ToString() : ""
             }).ToArray()
        };


  //client code

 success: function (data) {

            bathyms = "{";

            for (var i = 0; i < data[1].count; i++) {

                bathyms += el[i].Id + " : " + el[i].date;

                alert(el[i].Id);
                alert(el[i].date);
                console.log(el[i].date);

                if (i != data[0].count) {

                    bathyms += ",";
                }

            }
            bathyms += "}";
        }

2 个答案:

答案 0 :(得分:1)

您的data是一个包含单个字段row的对象,其中包含一个对象数组。因此,迭代应如下所示:

for (var i = 0; i < data.rows.length; i++) {
    var element = data.rows[i];
    // use element.Id, element.count and element.date

答案 1 :(得分:0)

假设你的模型是这样的 -

public class Data
{
    public int Id { get; set; }
    public int Count { get; set; }
    public string Date { get; set; }
}

你正在返回像这样的Array对象的JsonResult -

    public ActionResult GetJson()
    {
        Data[] a = new Data[2];
        a[0] = new Data() { Count = 10, Id = 1, Date = "2/19/2014" };
        a[1] = new Data() { Count = 20, Id = 2, Date = "3/19/2014" };

        return new JsonResult() { Data = a };
    }

然后,您可以通过以下方式在JQuery中调用此操作 -

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    function submitForm() {
        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("GetJson")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                $.each(data, function (key, value) {
                    alert(value.Id + ' ' + value.Count + ' ' + value.Date);
                });
            },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()" />

请注意以下代码将迭代数组 -

        success: function (data) {
            $.each(data, function (key, value) {
                alert(value.Id + ' ' + value.Count + ' ' + value.Date);
            });

输出将是基于数组中N个元素的N个警报,如下所示 -

enter image description here