KoGrid with KnockoutJS Simple Grid Set Up

Recently we took a look at implementing KoGrid which utilizes KnockoutJS.  This is a brief set up that I go going by pulling a data set from our controller.  First let’s look into the JavaScript and how all this happens.  Let’s look at the document initialization method first.

$(function () {
    var $scvm = new ConfigsViewModel();  //Create New Instance of our ViewModel
    $scvm.LoadConfigurations();  //Calls the load function in our ViewModel

This is all pretty straight forward.  So let’s take a bit deeper look into the ConfigsViewModel().  In here we will create our observableArray() and load our data.

var ConfigsViewModel = function () {
var self = this;

    //#region Observables
    self.ConfigurationsMin = ko.observableArray();

    self.LoadConfigurations = function () {
        $.post("/Config/Search", function (data) {
            var viewModel = {
                ConfigurationsMin: ko.observableArray(JSON.parse(data))

            //Activates knockoutjs so the browser knows what to do with data-bind in markup html.

Here you can see the LoadConfigurations function that gets call when the dom loads.  Within this function it’s doing an Ajax post which returns a serialized result.

JavaScriptSerializer s = new JavaScriptSerializer();
string json = s.Serialize(results);

return json;

Since we are serializing the results we do a quick JSON.parse which will split the data out into a JSON object that the grid will recognize.  This is all relatively simple and gets a start to pull data back.  Now let’s look at the mark up of the grid.

Here is the whole mark up and we will dig into it.

<div id="table_words" class="someStyles" data-bind="koGrid: { 'data': ConfigurationsMin }">

There are a few key points for this intro into KoGrid.  First, you can see using the data-bind element we are signaling koGrid which has an element called data.  Here we assign data with the observableArray of ConfigurationsMin.  If you remember, we created and applied our data to this object. ConfigurationsMin: ko.observableArray(data).  This is the bare bones of KoGrid and knockout; but it gets a grid up and running with doing an Ajax call to get some data to populate the grid with.

2 thoughts on “KoGrid with KnockoutJS Simple Grid Set Up

Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile