2014-02-19 30 views
0

我想遍歷從日控制器我想陣列的JSON數組知道我怎麼會遍歷它我怎麼能遍歷數組的JSON數組

我需要幫助:否能幫助我,我新到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 += "}"; 
     } 

回答

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 
0

說,如果你有你的模型是這樣 -

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

你如同該返回數組對象的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