J.Doe
J.Doe

Reputation: 3

Count the number of objects returned in an Ajax Request

My ajax request returns an IEnumerable UpcomingGigs, I'd like to count how many Gigs were returned per request. I've made various attempts at this, however each attempt includes a count of the property values too, and therefore not an accurate result.

Console.log(data.Length); var count=Object.keys(data).length;

ajax data response:

both values return the same incorrect result.

public ActionResult FetchGigs(int skip, int take)
        {
            var upcomingGigs = _context.Gigs
                                .Include(g => g.Artist)
                                .Where(g => g.DateTime > DateTime.Now)
                                .OrderBy(d => d.DateTime)
                                .Skip(skip).Take(take);

            var viewModel = new GigsViewModel
            {
                UpcomingGigs = upcomingGigs
            };
            return PartialView("FetchGigs", viewModel);
        } 

ViewModel

Ajax

    public class GigsViewModel
        {
            public IEnumerable<Gig> UpcomingGigs { get; set; }
            public int TotalGigs { get; set; }
            public bool ShowActions { get; set; }
            public string Heading { get; set; }
        }

$(window).scroll(function () {
                if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
                    $.ajax({
                        type: "GET",
                        url: "@Url.Action("FetchGigs")",
                        data: { skip: skip, take: take },
                        success: function (data) {

                            console.log(data.GigsViewModel.gigId.);

                            $(".result").append(data);
                        }
                    })
                }
            });

Upvotes: 0

Views: 2260

Answers (1)

Shyju
Shyju

Reputation: 218722

There are multiple ways to do this. One way is to add a data attribute the ul element you are rendering from the partial view and store the item count in that. You can use the IEnumerable.Count() method.

@model YourNamespace.GigsViewModel
<ul data-itemcount="@Model.UpcomingGigs.Count()">
    @foreach (var item in Model.UpcomingGigs)
    {
        <li>@item.Title</li>
    }
</ul>

Now in your ajax success event, parse the response received from the server using $.parseHTML and then reading the data attribute value

success: function (data) {
    var html =$.parseHTML(data);
    var itemCount = $(html).data("itemcount");
    alert(itemCount);
}

Another option is to use the find method to get the list item array and get it's length.

success: function(data) {
    var html = $.parseHTML(data);
    var itemCount = $(html).find("li").length;
    alert(itemCount);
}

I would go with the first approach as i do not like my browser doing so much of work. (It has to loop through the dom elements here to get the count)

Upvotes: 1

Related Questions