If you find this article useful, consider making a small donation to show your support for this web site and its content.
Free app Developer Interview available here.

Available on the iPhone App Store
Available on the Google Play
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.



Knockoutjs grid with Asp.net

by Farooq Kaiser 23. June 2012 05:56

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.

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’s template and Knockoutjs’s mapping plugin.

Grid UI

knockoutjs

First, define a C# model for the data

   1:  public class DataModel
   2:  {
   3:      public string name { get; set; }
   4:      public Int32 id { get; set; }
   5:      public double price { get; set; }
   6:  }

HTTP Handler

   1:  public class Handler1 : IHttpHandler{
   2:   
   3:          public void ProcessRequest(HttpContext context)
   4:          {
   5:   
   6:              var lstData = new System.Collections.Generic.List<DataModel>();
   7:   
   8:              for (Int32 i = 1; i < 75; i++)
   9:              {
  10:                  var dm = new DataModel();
  11:                  dm.name = string.Format("{0}{1}","Kaiser", i);
  12:                  dm.id = i;
  13:                  dm.price = 10.75;
  14:                  lstData.Add(dm);
  15:              }
  16:   
  17:              var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
  18:              var result = serializer.Serialize(lstData);
  19:   
  20:              context.Response.ContentType = "application/json";
  21:              context.Response.ContentEncoding = System.Text.Encoding.UTF8;
  22:              context.Response.Write(result);
  23:          }

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.

   1:  <system.web>
   2:      <httpHandlers>
   3:        <add verb="*" path="*/knockout/*" type="WebApplication2.Handler1,WebApplication2"/>
   4:      </httpHandlers>

Client-side View Model:

Now, include the jQuery, Knockoutjs, simpleGrid,mappingand Jquery templateJavaScript files as follows:

   1:  <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
   2:  <script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
   3:  <script src="Scripts/jquery.tmpl.min.js" type="text/javascript"></script>
   4:  <script src="Scripts/knockout.simpleGrid.js" type="text/javascript"></script>
   5:  <script src="Scripts/knockout.mapping-latest.js" type="text/javascript"></script>

Initialize the view model:

   1:   var ViewModel = function () {
   2:           var self = this;
   3:           this.initialized = ko.observable(false);
   4:           this.items = new ko.observableArray();
   5:  }
   6:   
   7:  var vModel = new ViewModel()
   8:       ko.applyBindings(vModel); 

Now, Initialize the simplegrid view model:

   1:   this.gridViewModel = new ko.simpleGrid.viewModel({
   2:               data: this.items,
   3:               columns: [
   4:                    { headerText: "Name", rowText: "name" },
   5:                    { headerText: "Id", rowText: "id" },
   6:                    { headerText: "Price", rowText: function (item) {
   7:                        return "$" +
   8:                          item.price()
   9:                    } 
  10:                    }
  11:                ],
  12:               pageSize: 10
  13:           });

Here is a html code for simplegrid:

   1:  <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.

   1:   $(document).ready(function () {
   2:               $.ajax({ url: "/knockout/Handler1.ashx",
   3:                   success: function (data) { 
   4:                       ko.mapping.fromJS(data, {}, self.items);
   5:                       self.initialized(true);
   6:                   }
   7:               });
   8:   
   9:           });

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.

   1:   this.addItem = function () {
   2:               self.items.push({ name: ko.observable($("#_name").val()),
   3:                   id: ko.observable($("#_id").val()),
   4:                   price: ko.observable($("#_price").val())
   5:               });
   6:           };
   7:   
   8:           this.removeItem = function (item) {
   9:               self.items.remove(item);
  10:           };
  11:   
  12:           this.sortByName = function () {
  13:               this.items.sort(function (a, b) {
  14:                   if (sortAsc)
  15:                       return a.id() > b.id() ? -1 : 1;
  16:                   else
  17:                       return a.id() < b.id() ? -1 : 1;
  18:               });
  19:   
  20:               sortAsc = !sortAsc;
  21:           };

Here is our html code for the buttons:

   1:  <button data-bind='click: addItem'>
   2:          Add item
   3:      </button>
   4:       
   5:      <button data-bind='click: sortByName'>
   6:          Sort by id
   7:      </button>
   8:       

Summary

This article showed how to extend grid functionality using KnockoutJS Framework. The sample code can be downloaded at CodeProject.

Currently rated 3.1 by 26 people

  • Currently 3.115385/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:


comments powered by Disqus
Jobs Autos Real estate Videos Power by Google