2014-11-08 29 views
1

我在處理ajax結果的數組列表時遇到了一個奇怪的問題。在處理ajax數組列表中遇到問題

我傳遞一個ID在功能和提取結果的該ID-

@for (var i = 0; i < Model.Count; i++) 
      { 
GetDates('@Model[i].contact_id'); 
} 

功能 -

var arrAcquiredDates = []; 
    function GetDates(contactid) { 
       $.ajax({ 
        url: '/Service/ServicesRenewalDates/', 
        type: 'POST', 
        data: { Id: contactid }, 
        success: function (data) { 
         console.log(data); 
         for (var i = 0; i < JSON.stringify(data.countof.Length) ; i++); 
         { 
          arrAcquiredDates.push('<tr><td colspan="4">' + data.list[i].DateAcquired + ' To ' + data.list[i].DateRenewal + '</td></tr>'); 
         } 
         $('#tl-' + contactid).after(arrAcquiredDates); 
        } 
       }); 
      } 

基礎上由此這個函數從控制器調用方法和回取結果與列表中的數組列表 -

public JsonResult ServicesRenewalDates(long? Id) 
     { 
      Bal b = new Bal(); 
      List<ServiceModel> services = new List<ServiceModel>(); 
      services = b.ServicesRenewalDates(Id); 
      return Json(new { list = services, countof = services.Count }, JsonRequestBehavior.AllowGet); 
     } 

見表 -

enter image description here

這裏是UI表的一部分。如果你注意到第一行返回的數字是2,所以ajax遞交循環2次,並獲取我在列表中追加的相關結果。 但是從圖像你可以在這裏看到,它只是扭轉想要的結果。其中Returned的數字是2;它返回一行,併爲1它返回兩行。

我遇到了Ajax處理中出錯的地方。

我的控制檯的結果是一樣的東西這個 -

enter image description here

現在最後的部分地方我在表 -

<table class="table table-responsive table-bordered table-striped"> 
       <thead> 
        <tr> 
         <th>Customer Name</th> 
         <th>Returned Times</th> 
        </tr> 
       </thead> 
       <tbody> 
        @foreach (var item in Model) 
        { 
         <tr id="[email protected]_id"> 
          <td>@item.customerName 
          </td> 
          <td>@item.countCustomers</td> 
         </tr> 
        } 
       </tbody> 
      </table> 

如何處理這個AJAX結果在渲染列表正確的方法?

+2

返回'countof'似乎沒有意義。所有你需要的是'return Json(list,JsonRequestBehavior.AllowGet);'。如果值在1和9之間,data.countof.Length將返回1,這樣就沒有任何意義(如果集合返回8個項目,它仍然只會循環一次)。並且你不斷追加新行到'arrAcquiredDates',這就是你看到這些結果的原因。 – 2014-11-08 06:50:27

回答

1

它沒有必要返回列表的數量和你的操作方法可以通過項目集合中被簡化爲

public JsonResult ServicesRenewalDates(long? Id) 
{ 
    Bal b = new Bal(); 
    List<ServiceModel> services = b.ServicesRenewalDates(Id); 
    return Json(services, JsonRequestBehavior.AllowGet); 
} 

然後在阿賈克斯成功回調循環建立一個錶行並將其附加到在DOM

success: function (data) { 
    $.each(data, function(index, item) { 
    var row = $('<tr></tr>').append($('<td colspan="4"></td>').text(item.DateAcquired + ' to ' + item.DateRenewal)); 
    $('#tl-' + contactid).after(row); 
    }); 

還要注意,如果services包含的不僅僅是DateAcquired其他和DateRenewal性質應創建匿名對象的集合,以傳送回客戶端的數據減少

services = b.ServicesRenewalDates(Id) 
    .Select(s => new 
    { 
    DateAcquired = s.DateAcquired, 
    DateRenewal = s.DateRenewal 
    });