JSON Binding to Grid and Monitoring with Knockout.js | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (215)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (220)Microsoft  (118)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (912)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (158)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (130)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (626)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (506)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (386)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (590)What's new  (331)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)

JSON Binding to Grid and Monitoring with Knockout.js

Bharath M.

 

This is another post on the flexibility of Syncfusion Grid’s client-side functionality. Here are the steps involved:

Grid preparation

In this post, we are going to play with JSON functionalities of the grid. I chose the JSON mode for the grid and Excel-like editing to ensure that the grid is responding to JSON changes.

@{ Html.Grid("Grid1")
   .ActionMode(ActionMode.JSON)
   .AllowKeyboardNavigation(true)
   .Column(column =>
    {
    column.Add(p => p.OrderID).HeaderText("Order ID").TextAlign(TextAlignment.Right).Width(100);
    column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(100);
    column.Add(p => p.EmployeeID).Width(100);
    column.Add(p => p.Freight).Width(100);
    })
   .ClientSideEvents(c => 
   c.QueryCellInfo("Grid1QueryCell") // This adds the Data-bind attribute to a grid cell.
   .OnActionComplete("ActionComplete")
   .OnToolbarClickEvent("ToolbarClicked"))
   .ToolBar(tools =>
   {
   tools.Add(GridToolBarItems.Update)
  .Add(GridToolBarItems.Cancel);
  })
  .Mappers(m => m.SaveAction("BulkSave"))
  .Editing(edit =>
  {
  edit.AllowEdit(true);
  edit.EditMode(GridEditMode.ManualExcel);//Specify the grid edit mode.
  edit.PrimaryKey(key => key.Add(p => p.OrderID));// Add primary key to primary key collections
  }).Render();
   }

Knockout’s ViewModel

Knockout.js is the better choice for dynamic UI updates without any glue-code or events. Here, the grid is bound with the “Editable Order” model from the server side. Since Knockout.js is model-based, we have to create a model on the client side also. The code for that is as follows:

 function OrderViewModel(data) {

   // Actual JSON from grid.
   this.data = data;
   // This is to detect changes in the model.
  this.isDirty = ko.observable(false);
  // Model properties.
  this.OrderID = ko.observable().extend({ AutoUpdate: { "model": this, "name": "OrderID" } });
  this.CustomerID = ko.observable().extend({ AutoUpdate: { "model": this, "name": "CustomerID" } });
  this.EmployeeID = ko.observable().extend({ AutoUpdate: { "model": this, "name": "EmployeeID" } });
  this.Freight = ko.observable().extend({ AutoUpdate: { "model": this, "name": "Freight" } });
  }
 // Created custom extender for auto-updating JSON data as well as the model.
  ko.extenders.AutoUpdate = function (target, options) {
  target(options.model.data[options.name]);
  target.subscribe(function (newValue) {
 // Notifying the model that it has been changed.
 if (!options.model.isDirty())
     options.model.isDirty(true);
    // Updating changed values to original JSON data.
   options.model.data[options.name] = newValue;
   return target;
  }

AutoUpdate is the custom extender for observables; it will take care of syncing a JSON data source between Knockout’s model and the grid’s data source.

We also need another model for storing the list of an OrderViewModel collection and binding it to a page.

function PageViewModel() {
this.dataSource = ko.observableArray([]);
 }

Integrating the Grid and Knockout’s ViewModel

For the integration, we are going to write code for setting the data-bind attributes to a grid cell and binding the grid’s HTML elements to Knockout.js.

The QueryCellInfo code adding the data-bind attribute is as follows:

function Grid1QueryCell(sender, args) {
   if (args.Column.Name) {
  var currentData = "dataSource()[" + args.Element.parentNode.rowIndex + "].";
  // Here we set the Knockout.js data-binding attribute.
  $(args.Element).attr("data-bind", "text: " + currentData + args.Column.Name + ",css: {updatedCell : " + currentData + "isDirty}");

  // text: is for updating cell values and
  // css: is for notifying the user that cells have been updated.
  }
 }

For binding the model, we have to use the grid’s OnActionComplete event, since during initial rendering the grid didn’t have data in it. Let me show you the code:

 // The jQuery ready event has been used to define the page view-model.

 $(function () {
    page = new PageViewModel();
   // Knockout.js binding can be applied to the whole page here.
    // ko.applyBindings(page);
   });
  // The grid's OnActionComplete event has been used to update Knockout’s data source.
  function ActionComplete(grid, args) {
  // Here we are setting the page data source.
    page.dataSource(ko.syncJsMap(grid.get_jsonModeMgr().get_dataSource(), OrderViewModel));
   // I'm going to enable all toolbar items.
   grid.gridtoolbar.Enable_All();
   // Clearing previous binding, if any.
   ko.cleanNode($(grid.get_element()).find(".GridContent").children().get(0));
   // Applying bindings to newly created content.
    ko.applyBindings(page, $(grid.get_element()).find(".GridContent").children().get(0));
   }
   // We need to set updatedRecords on the ToolbarClicked event.
   function ToolbarClicked(grid, args) {
   // Getting the changed JSON data.
   var koChanges = page.dataSource()
        .filter(
  function (obj) { return obj.isDirty(); });
   // Marking the grid as Editing.
   grid._edit._isEdit = true;
   // Updating the changed records to the grid.
   if (grid._edit._updatedRecords) {
    // Merging the changes if there are any updates from the grid.
   for (var i = 0; i < koChanges.length; i++) {
   if (grid._edit._updatedRecords.indexOf(koChanges[i].data) == -1)
   grid._edit._updatedRecords.push(koChanges[i].data);
  }
  }
  else 
      grid._edit._updatedRecords = ko.utils.arrayMap(koChanges, function (obj) { return obj.data; });
 }

syncJsMap is the Knockout.js extension I created for converting the JSON data source to Knockout’s model-based data source. Here is the code I used:

ko.syncJsMap = function (obj, viewModel) {
 if (obj.length) {
  var mapArray = [];
  for (var i = 0; i < obj.length; i++) {
       mapArray.push(new viewModel(obj[i]));
        }
   return mapArray;
    }
  }

Playing with the JSON Collection

Now it’s time to play with the results of the previous processes. I have written some HTML and JavaScript to produce the following functionality:

clip_image002

Upon clicking Change, the concerned JSON data will be updated using Knockout’s ViewModel. The code for that is as follows:

$("#butChange").click(function () {
  var rowIndex = parseInt($("#rowIndex").val(), 10);
  var columnName = $("#selectColumn").val()
  var value = $("#change").val();
   // The JSON collection can be changed like this. This will update the grid's UI as well as the data source.
   page.dataSource()[rowIndex][columnName](value);
  });

Once Change is clicked, you’ll see the updates in the grid as well. Please refer to the following screenshot:

clip_image004

You can see in the previous screenshot that the updated row will have a red mark. Click on the save icon in the grid’s toolbar to store data in the database and clear all dirty items.

clip_image006

You can find a downloadable version of this sample here: https://www.syncfusion.com/downloads/Support/DirectTrac/General/JsonCollection%20Change576454545.zip

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed