Tuesday, March 31, 2015

Cool Stuff, Editable Grid with Automatic Changes saved

This is ideal for checkboxes.  Placing a grid in .Batch(true) and .ServerOperation(false) allows the user to click on a cell to edit it's value.  Usually there is a "Save Changes" button they have to click to save all their changes.

In this solution we allow users to check or uncheck checkboxes - when they change the state of a checkbox, it updates the database automatically - no need to have the user click the save changes button.

Create a template column:

  c.Bound("ArticleIsMine").ClientTemplate("<input type='checkbox' #= ArticleIsMine? checked='checked': checked='' # class='chkbx' />");  

Add a change event to the grid's datasource:
  .DataSource(data => data.Ajax()  
      .Model( m =>  
    {  
      m.Id("Id");  
      m.Field(f => f.PubDate).Editable(false);  
      m.Field(f => f.Title).Editable(false);  
    })  
    .Events(e => e.Change("dataChange"))  

Add the JavaScript event and code for the template checkbox:
 $(document).ready(function () {  
     kendo.data.DataSource.prototype.options.autoSync = true;  
     $('#gvPubs').on('click', '.chkbx', function () {  
       var checked = $(this).is(':checked');  
       var g = $('#gvPubs').data().kendoGrid;  
       g.closeCell();  
       var dataItem = g.dataItem($(this).closest('tr'));  
       var col = $(this).closest('td');  
       g.editCell(col);  
       dataItem.set(g.columns[col.index()].field, checked);  
       g.closeCell(col);  
     });  
the sync call does the actual save:
  function dataChange(e) {  
     if (e.action == "itemchange") {  
       this.sync();  
     }  
   }  

The checkbox javascript code updates the in memory model with the new value of the control, the dataChange function saves the changes to the database (calls the grid's Update method).

BTW, the code formatting for this blog post was done using this handy tool:
http://codeformatter.blogspot.com/

No comments:

Post a Comment