Thursday, September 18, 2014

Display checkboxes for bit or bit? data types in Kendo Grid, disabled in Read mode, enabled for edit mode


Kendo Grid - How to have read only checkboxes displayed for a bit field and allow them to be checked/unchecked when in edit mode.


Note:  My preference is to use Kendo MVC - Razor syntax.

1.  Create a template in your grid columns like this:

c.Bound(m => m.rnPagerPhoneExtension).Title("EXTN").Width(200);

                            c.Template(@<text></text>).ClientTemplate("<input type='checkbox' disabled='disabled'  #= PCP ? checked='checked':'' # class='PCPchkbx' />")
                   .HeaderTemplate("PCP").Width(200);

In the above, note that the checkbox is disabled and has a classname assigned to it.  #= PCP # is Kendo syntax to bind my database bit column "PCP" to this checkbox.


2.  Bind the grid Edit event to a javascript function.

 @(Html.Kendo().Grid<Model.Models.blah>()
.Name("gvBlah")
.Events(e =>
{
    e.Edit("editmode");
})
        .Columns(c =>

3.  Create the javascript function:

 //Using the classname enable checkboxes if in edit mode, they are disabled for read mode:
    function editmode(e) {
        $(".PCPchkbx").attr('disabled', false);
    }

What this does is that when the grid goes into edit mode, the checkbox will be enabled.  Note that $(".PCPchkbx") is Jquery syntax for find by classname.

4.  Finally, create a function bound to the checkbox click event that will pass the checked status of the checkbox to the model data, so it's saved to the database

//set model data to checkbox checked value, used when saving
    $(function () {
        $('#gvBlah').on('click', '.PCPchkbx', function () {
            var checked = $(this).is(':checked');
            var grid = $('#gvBlah').data().kendoGrid;
            var dataItem = grid.dataItem($(this).closest('tr'));
            dataItem.set('PCP', checked);
        })
    })


No comments:

Post a Comment