I have strange problem in handling array list of ajax result.
I am passing an ID in function and fetching results on the basis of that Id-
@for (var i = 0; i < Model.Count; i++)
{
GetDates('@Model[i].contact_id');
}
Function-
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);
}
});
}
Hereby this function invokes method from the controller and fetches back result with array list in it-
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);
}
See in table-

Here is the part of UI table. If you note the returned number is 2 for first row, So ajax delivers loop for 2 times and fetches me related results that I am appending in the list.
But from image you can see it here that it does just reverse of wanted result. Where Returned number is 2; it returns one row and for 1 it returns two rows.
I am experiencing something went wrong in ajax handling.
My console result is something like this-

And now at last the part where I am rendering list in table-
<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>
How do I handle this ajax result in right way?
countof. All you need isreturn Json(list, JsonRequestBehavior.AllowGet);. Alsodata.countof.Lengthwill return1if the value is between 1 and 9 so that makes no sense (if the collection returned 8 items its still only going to loop once). And you keep appending new rows toarrAcquiredDates, which is why you are seeing these results.