Adding list of items to Owl Carousel 2 dynamically in Asp.net/MVC

1.7k views Asked by At

I have an Owl Carousel in my view and items that are loading to the carousel are from a partial-view like below:

@model CalendarComponets.Models.ViewModel.EventWidgetViewModel

    <div class="container">
            <div class="col-md-12 owl-carousel repeater">
                    @Html.Partial("_paginator", (Model.AllCalendarDate as List<CalendarComponets.Models.Data.DateTimer>))
            </div>
            <span class="more-trigger">
                <div id="more-trigger" class="space-top space-bottom"><a class="btn btn-md btn-primary btn-center"><i class="left fa fa-refresh"></i>More</a></div>
            </span>
     </div>

And they are populated in my controller:

public ActionResult GetStaff()
{
         EventWidgetViewModel _vm = new EventWidgetViewModel();
         Repository _repository = new Repository();
        _vm.AllCalendarDate = _repository.RangeDate().Take(7).ToList();
        _vm.AllReservedHours = _repository.GetAvailableHours(DateTime.Now);
        return PartialView("_calendar", _vm);
}

And my _paginator partialview is:

@model List<CalendarComponets.Models.Data.DateTimer>


@foreach (var item in Model)
            {

    <input type="button" id="@item.Id" value="@item.Date" style="background-color: cadetblue; padding: 25px; text-align: center; border: 1px solid" />
}

Now I call an ajax to take the next n list from controller, and on success it should append the data to my carousel but it doesn't and append the data under my carousel:

    //ajax to get next Dates
    var page = 1; 
    $(document).on('click', '#more-trigger', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'GET',
            url: '/EventWidget/GetNextDateCollection',
            data: {
                pageNumber: page++
            },
            success: function (data) {
                 alert(data);             

                 var carousel = $(".owl-carousel");
                 carousel.owlCarousel({
                     nav: true,
                     navText: ['<i class="fa fa-arrow-left"></i>',
                         '<i class="fa fa-arrow-right" id="arrowRight" />'],
                     items: 7
                 });

                $(".repeater").append(data);

            },
            error: function (data) {
                alert("Serious Issue has happened while getting NextDateCollection");
            }
        });
    });

And in my Controller GetNextDateCollection action called which returns the _paginator partialview:

public ActionResult GetNextDateCollection(string pageNumber)
{
    if(!string.IsNullOrEmpty(pageNumber))
    {
        int pageIndex = Convert.ToInt32(pageNumber);
        var _list = _repository.RangeDate()
            .Skip(7 * pageIndex)
            .Take(7).ToList();
        return PartialView("_paginator", _list);

    }
    else
    {
        return PartialView("_paginator");
    }

}

First time it loads correctly and shows 7 items from my list in the carousel but on second time it doesn't and just append the data under my carousel, What have I done wrong? How can I add the return data to my carousel?

2

There are 2 answers

0
Masoud Andalibi On BEST ANSWER

For all the poor souls that are using this plugin (Owl Carousel) without documentation. For adding the items into the carousel you have to use this trigger add.owl.carousel.

Thanks to Gavin Harrison, I've found the solution and I am going to share it with you all.

Basically on the success of my AJAX:

   success: function (data) {

        // Getting the owl carousel
         var carousel = $(".owl-carousel");
         //creating an array
         var elementArray = []; 
        // splitting the returned data in to an array 
//element array split

             elementArray = data.split('/>');

        // Looping through each element and adding it to the carousel
         for (i = 0; i < elementArray.length; i++) {
             // Validating that the array element is not empty
             if (elementArray[i] != '' || elementArray[i] != ' />') {

             $('.owl-carousel').trigger('add.owl.carousel', [elementArray[i] + '/>']).trigger('refresh.owl.carousel');
             }
         }
    }
3
Gavin Harrison On

The issue you are having is because the first time the page loads owl initializes it's self which shows the items correctly. Then when the AJAX request updates the slider owl carousel is all ready running and knows nothing about the new items you are manually inserting.

To dynamically add new items to the carousel you need to tell owl carousel to inset each new item by doing the following:

// Getting the owl carousel
var carousel = $(".owl-carousel");

// splitting the returned data in to an array
var elementArray = data.split('/>');

// Looping through each element and adding it to the carousel
for(i = 0; i < data.length; i++)
{
    // Validating that the array element is not empty
    if(data[i] != '')
    {
        // Adding the array element to the carousel.
        // Also adding back on the chars that was used during the splitting.
        carousel.add(data[i] + '/>');
    }
}

Link to the owl carousel source code showing the Add method