2014-11-08 93 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 
    });