Click here to Skip to main content
15,881,882 members
Articles / Web Development / ASP.NET

Knockoutjs grid with Asp.net

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
23 Jun 2012CPOL1 min read 41.6K   1.6K   27   3
This article explains how to use Knockoutjs�s plug-in simpleGrid with asp.net using HTTP handler.

  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    

Image 1

Using the code  

First, define a C# model for the data: 

C#
public class DataModel
{
    public string name { get; set; }
    public Int32 id { get; set; }
    public double price { get; set; }
} 

HTTP Handler 

C#
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. 

XML
<system.web>
    <httpHandlers>
      <add verb="*" path="*/knockout/*" type="WebApplication2.Handler1,WebApplication2"/>
    </httpHandlers>  

Client-side View Model:  

Now, include the jQueryKnockoutjssimpleGrid,mappingand Jquery templateJavaScript files as follows: 

JavaScript
<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:

JavaScript
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: 

JavaScript
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:

HTML
<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.

JavaScript
$(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.

JavaScript
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: 

HTML
<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. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questiondelete button Pin
Carlos Bolaños5-Dec-13 10:58
Carlos Bolaños5-Dec-13 10:58 
AnswerRe: delete button Pin
1stefan26-Mar-15 4:44
1stefan26-Mar-15 4:44 
QuestionMicrosoft JScript runtime error: Object doesn't support property or method 'tmpl' Pin
Member 793021318-Apr-13 19:23
Member 793021318-Apr-13 19:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.