Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist CheckBox State in Telerik MVC Grid While Paging in ASP.NET MVC Application

I am using Telerik MVC Grid where one of the columns is checkboxes. If I select checkboxes and then go to page 2 and then come back to page 1 all the checkboxes are gone. Which is of course the way HTTP works. Now, I put all the selected checkboxes inside the hidden field but since the grid does some sort of postback my hidden field is cleared next time.

like image 474
johndoe Avatar asked Dec 22 '22 18:12

johndoe


1 Answers

If you're using Client Side data binding you can use the javascript/jquery below to maintain checkbox state.

Maintain checkbox state:

var selectedIds = [];

$(document).ready(function () {
    //wire up checkboxes.
    $('#YOUR_GRID_ID :checkbox').live('change', function (e) {
        var $check = $(this);
        console.log($check);
        if ($check.is(':checked')) {
            //add id to selectedIds.
            selectedIds.push($check.val());
        }
        else {
            //remove id from selectedIds.
            selectedIds = $.grep(selectedIds, function (item, index) {
                return item != $check.val();
            });
        }
    });
});

Restore checkbox state after data binding:

function onDataBound(e) {
    //restore selected checkboxes.
    $('#YOUR_GRID_ID :checkbox').each(function () {
        //set checked based on if current checkbox's value is in selectedIds.
        $(this).attr('checked', jQuery.inArray($(this).val(), selectedIds) > -1);
    });
}

A more verbose explanation available on my blog: http://blog.cdeutsch.com/2011/02/preserve-telerik-mvc-grid-checkboxes.html

like image 194
cdeutsch Avatar answered Dec 29 '22 12:12

cdeutsch