Download sample
Introduction
Knockoutjs implements the Model-View-ViewModel pattern for JavaScript. This article explains how to use Knockoutjs's plug-in simpleGrid with asp.net using HTTP handler. It can be used where dynamic UI is required such as adding/removing rows to the grid.
Background
Here is an original demo at Knockoutjs.I have extended the functionality of original demo to use Asp.net HTTP handler with Ajax. The simpleGrid plugin also uses jquery template and Knockoutjs mapping plugin.
Grid UI
Using the code
First, define a C# model for the data:
public class DataModel
{
public string name { get; set; }
public Int32 id { get; set; }
public double price { get; set; }
}
HTTP Handler
public class Handler1 : IHttpHandler{
public void ProcessRequest(HttpContext context)
{
var lstData = new System.Collections.Generic.List<DataModel>();
for (Int32 i = 1; i < 75; i++)
{
var dm = new DataModel();
dm.name = string.Format("{0}{1}","Kaiser", i);
dm.id = i;
dm.price = 10.75;
lstData.Add(dm);
}
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var result = serializer.Serialize(lstData);
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.Write(result);
}
In above Http handler code, we are returning Json data to the client. Next, we need to register our Http Handler in web config as shown below.
<system.web>
<httpHandlers>
<add verb="*" path="*/knockout/*" type="WebApplication2.Handler1,WebApplication2"/>
</httpHandlers>
Client-side View Model:
Now, include the jQuery, Knockoutjs, simpleGrid,mappingand Jquery templateJavaScript files as follows:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="Scripts/jquery.tmpl.min.js" type="text/javascript"></script>
<script src="Scripts/knockout.simpleGrid.js" type="text/javascript"></script>
<script src="Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
Initialize the view model:
var ViewModel = function () {
var self = this;
this.initialized = ko.observable(false);
this.items = new ko.observableArray();
}
var vModel = new ViewModel()
ko.applyBindings(vModel);
Now, Initialize the simplegrid view model:
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items,
columns: [
{ headerText: "Name", rowText: "name" },
{ headerText: "Id", rowText: "id" },
{ headerText: "Price", rowText: function (item) {
return "$" +
item.price()
}
}
],
pageSize: 10
});
Here is a html code for simplegrid:
<div data-bind='simpleGrid: gridViewModel'> </div>
Now make an ajax call to Http handler when the document is ready and returned data will be bound to underlying observable array using mapping plugin.
$(document).ready(function () {
$.ajax({ url: "/knockout/Handler1.ashx",
success: function (data) {
ko.mapping.fromJS(data, {}, self.items);
self.initialized(true);
}
});
});
Next, we will be adding our add/sort buttons to the items observable array in the underlying view model and the UI will take care of updating itself.
this.addItem = function () {
self.items.push({ name: ko.observable($("#_name").val()),
id: ko.observable($("#_id").val()),
price: ko.observable($("#_price").val())
});
};
this.removeItem = function (item) {
self.items.remove(item);
};
this.sortById = function () {
this.items.sort(function (a, b) {
if (sortAsc)
return a.id() > b.id() ? -1 : 1;
else
return a.id() < b.id() ? -1 : 1;
});
sortAsc = !sortAsc;
};
Here is our html code for the buttons:
<button data-bind='click: addItem'>
Add item
</button>
<button data-bind='click: sortById'>
Sort by id
</button>
Summary
This article showed how to extend grid functionality using KnockoutJS Framework.