Click here to Skip to main content
Click here to Skip to main content
Go to top

Knockoutjs grid with Asp.net

, 23 Jun 2012
Rate this:
Please Sign up or sign in to vote.
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    

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 jQueryKnockoutjssimpleGrid,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. 

License

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

Share

About the Author

Farooq Kaiser
Software Developer (Senior) http://www.Fairnet.com
Canada Canada
12+ years of complete software development life cycle experience for web based applications and multi-tier client-server desktop, primarily using LINQ, WCF, WWF, C#, ASP.NET, XML, XSLT, AJAX, Winforms,Visual Basic, JavaScript, JQuery, Google APIs, C++, VB.NET, C, ATL/COM, Open XML. Extensively involved in the requirement analysis, feasibility study, conceptualization, planning, architecture/design, configuration, development, quality assurance, implementation and release of the software products.

Comments and Discussions

 
Questiondelete button PinmemberCarlos Bolaños5-Dec-13 10:58 
QuestionMicrosoft JScript runtime error: Object doesn't support property or method 'tmpl' PinmemberMember 793021318-Apr-13 19:23 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 23 Jun 2012
Article Copyright 2012 by Farooq Kaiser
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid