CRUD Operations Using Web API 2 And Knockout.js

Introduction

In this article, I will demonstrate how we can perform simple CRUD (Create, Read, Update, Delete) operations using ASP.NET Web API 2 and Knockout.js library. Here, the purpose is to give you an idea of how to use knockout.js with Web API 2. I hope you will like this.

Prerequisites

As I said before, to achieve our requirement, you must have Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.

In this post, we are going to

  • Create MVC application.
  • Configuring Entity framework ORM to connect to database.
  • Implementing all http Services needed.
  • Calling Services using Knockout.js library.

So, let’s understand a bit about knockout.js

What’s Knockout.js?

Knockout is a JavaScript library that helps you to create a rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Headline features,

  • Elegant dependency tracking - automatically updates the right parts of your UI whenever your data model changes.
  • Declarative bindings - a simple and obvious way to connect parts of your UI to your data model. You can construct complex dynamic UIs easily using arbitrarily nested binding contexts.
  • Trivially extensible - implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.

SQL Database part

Here, find the script to create database and table.

  1. Create Database  
  2. USE [master]  
  3. GO  
  4.   
  5. /****** Object  Database [DBCustomer]    Script Date 3/4/2017 32357 PM ******/  
  6. CREATE DATABASE [DBCustomer]  
  7.  CONTAINMENT = NONE  
  8.  ON  PRIMARY   
  9. NAME = N'DBCustomer', FILENAME = N'c\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBCustomer.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
  10.  LOG ON   
  11. NAME = N'DBCustomer_log', FILENAME = N'c\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBCustomer_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
  12. GO  
  13.   
  14. ALTER DATABASE [DBCustomer] SET COMPATIBILITY_LEVEL = 110  
  15. GO  
  16.   
  17. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
  18. begin  
  19. EXEC [DBCustomer].[dbo].[sp_fulltext_database] @action = 'enable'  
  20. end  
  21. GO  
  22.   
  23. ALTER DATABASE [DBCustomer] SET ANSI_NULL_DEFAULT OFF   
  24. GO  
  25.   
  26. ALTER DATABASE [DBCustomer] SET ANSI_NULLS OFF   
  27. GO  
  28.   
  29. ALTER DATABASE [DBCustomer] SET ANSI_PADDING OFF   
  30. GO  
  31.   
  32. ALTER DATABASE [DBCustomer] SET ANSI_WARNINGS OFF   
  33. GO  
  34.   
  35. ALTER DATABASE [DBCustomer] SET ARITHABORT OFF   
  36. GO  
  37.   
  38. ALTER DATABASE [DBCustomer] SET AUTO_CLOSE OFF   
  39. GO  
  40.   
  41. ALTER DATABASE [DBCustomer] SET AUTO_CREATE_STATISTICS ON   
  42. GO  
  43.   
  44. ALTER DATABASE [DBCustomer] SET AUTO_SHRINK OFF   
  45. GO  
  46.   
  47. ALTER DATABASE [DBCustomer] SET AUTO_UPDATE_STATISTICS ON   
  48. GO  
  49.   
  50. ALTER DATABASE [DBCustomer] SET CURSOR_CLOSE_ON_COMMIT OFF   
  51. GO  
  52.   
  53. ALTER DATABASE [DBCustomer] SET CURSOR_DEFAULT  GLOBAL   
  54. GO  
  55.   
  56. ALTER DATABASE [DBCustomer] SET CONCAT_NULL_YIELDS_NULL OFF   
  57. GO  
  58.   
  59. ALTER DATABASE [DBCustomer] SET NUMERIC_ROUNDABORT OFF   
  60. GO  
  61.   
  62. ALTER DATABASE [DBCustomer] SET QUOTED_IDENTIFIER OFF   
  63. GO  
  64.   
  65. ALTER DATABASE [DBCustomer] SET RECURSIVE_TRIGGERS OFF   
  66. GO  
  67.   
  68. ALTER DATABASE [DBCustomer] SET  DISABLE_BROKER   
  69. GO  
  70.   
  71. ALTER DATABASE [DBCustomer] SET AUTO_UPDATE_STATISTICS_ASYNC OFF   
  72. GO  
  73.   
  74. ALTER DATABASE [DBCustomer] SET DATE_CORRELATION_OPTIMIZATION OFF   
  75. GO  
  76.   
  77. ALTER DATABASE [DBCustomer] SET TRUSTWORTHY OFF   
  78. GO  
  79.   
  80. ALTER DATABASE [DBCustomer] SET ALLOW_SNAPSHOT_ISOLATION OFF   
  81. GO  
  82.   
  83. ALTER DATABASE [DBCustomer] SET PARAMETERIZATION SIMPLE   
  84. GO  
  85.   
  86. ALTER DATABASE [DBCustomer] SET READ_COMMITTED_SNAPSHOT OFF   
  87. GO  
  88.   
  89. ALTER DATABASE [DBCustomer] SET HONOR_BROKER_PRIORITY OFF   
  90. GO  
  91.   
  92. ALTER DATABASE [DBCustomer] SET RECOVERY SIMPLE   
  93. GO  
  94.   
  95. ALTER DATABASE [DBCustomer] SET  MULTI_USER   
  96. GO  
  97.   
  98. ALTER DATABASE [DBCustomer] SET PAGE_VERIFY CHECKSUM    
  99. GO  
  100.   
  101. ALTER DATABASE [DBCustomer] SET DB_CHAINING OFF   
  102. GO  
  103.   
  104. ALTER DATABASE [DBCustomer] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )   
  105. GO  
  106.   
  107. ALTER DATABASE [DBCustomer] SET TARGET_RECOVERY_TIME = 0 SECONDS   
  108. GO  
  109.   
  110. ALTER DATABASE [DBCustomer] SET  READ_WRITE   
  111. GO  
  112.   
  113.   
  114. Create Table  
  115. USE [DBCustomer]  
  116. GO  
  117.   
  118. /****** Object  Table [dbo].[Customer]    Script Date 3/4/2017 32449 PM ******/  
  119. SET ANSI_NULLS ON  
  120. GO  
  121.   
  122. SET QUOTED_IDENTIFIER ON  
  123. GO  
  124.   
  125. SET ANSI_PADDING ON  
  126. GO  
  127.   
  128. CREATE TABLE [dbo].[Customer](  
  129.     [CustID] [int] IDENTITY(1,1) NOT NULL,  
  130.     [FirstName] [varchar](50) NULL,  
  131.     [LastName] [varchar](50) NULL,  
  132.     [Email] [varchar](50) NULL,  
  133.     [Country] [varchar](50) NULL,  
  134.  CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED   
  135. (  
  136.     [CustID] ASC  
  137. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  138. ON [PRIMARY]  
  139.   
  140. GO  
  141.   
  142. SET ANSI_PADDING OFF  
  143. GO   

Create your MVC application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.


Next, new dialog will pop up for selecting the template. We are going choose Web API template and click Ok button.


After creating our project, we are going to add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

For adding ADO.NET Entity Framework, right click on the project name, click Add > Add New Item. Dialog box will pop up. Inside Visual C#, select Data >> ADO.NET Entity Data Model, and enter a name for your Dbcontext model as CustomerModel.

Finally,  click Add.
 

Next, we need to choose EF Designer from database as model container.


As you can see below, we need to select Server name, then via drop down list, connect to a database panel. You should choose your database name. Finally, click OK.




Now, the dialog Entity Data Model Wizard will pop up for choosing the object which we need to use. In our case, we are going to choose Customers table and click "Finish" button.

Finally, we see that EDMX model generates a Customer class.
 



Create a Controller

Now, we are going to create a Controller. Right click on the Controllers folder and go to Add > Controller> selecting Web API 2 Controller with actions using Entity Framework > click Add.


In the snapshot given below, we are providing three important parameters

  • Model class Customer represents the entity that should be used for CRUD operations.
  • Data context class used to establish connection with database.
  • Finally, we need to name our Controller (in this case Customers Controller).


As we already know, Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients including browsers and mobile devices.

It has four methods where

  • Get is used to select data.
  • Post is used to create or insert data.
  • Put is used to update data.
  • Delete is used to delete data.

CustomersController.cs 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web.Http;  
  10. using System.Web.Http.Description;  
  11. using CustomerApp;  
  12. using CustomerApp.Models;  
  13.   
  14. namespace CustomerApp.Controllers  
  15. {  
  16.     public class CustomersController  ApiController  
  17.     {  
  18.         //DbContext  
  19.         private DBCustomerEntities db = new DBCustomerEntities();  
  20.   
  21.         // GET api/Customers  
  22.         public IQueryable<Customer> GetCustomers()  
  23.         {  
  24.             return db.Customers;  
  25.         }  
  26.   
  27.          
  28.   
  29.         // PUT api/Customers/5  
  30.         [ResponseType(typeof(void))]  
  31.         public IHttpActionResult PutCustomer(int id, Customer customer)  
  32.         {  
  33.             if (!ModelState.IsValid)  
  34.             {  
  35.                 return BadRequest(ModelState);  
  36.             }  
  37.   
  38.             if (id != customer.CustID)  
  39.             {  
  40.                 return BadRequest();  
  41.             }  
  42.   
  43.             db.Entry(customer).State = EntityState.Modified;  
  44.   
  45.             try  
  46.             {  
  47.                 db.SaveChanges();  
  48.             }  
  49.             catch (DbUpdateConcurrencyException)  
  50.             {  
  51.                 if (!CustomerExists(id))  
  52.                 {  
  53.                     return NotFound();  
  54.                 }  
  55.                 else  
  56.                 {  
  57.                     throw;  
  58.                 }  
  59.             }  
  60.   
  61.             return StatusCode(HttpStatusCode.NoContent);  
  62.         }  
  63.   
  64.         // POST api/Customers  
  65.         [ResponseType(typeof(Customer))]  
  66.         public IHttpActionResult PostCustomer(Customer customer)  
  67.         {  
  68.             if (!ModelState.IsValid)  
  69.             {  
  70.                 return BadRequest(ModelState);  
  71.             }  
  72.   
  73.             db.Customers.Add(customer);  
  74.             db.SaveChanges();  
  75.   
  76.             return CreatedAtRoute("DefaultApi"new { id = customer.CustID }, customer);  
  77.         }  
  78.   
  79.         // DELETE api/Customers/5  
  80.         [ResponseType(typeof(Customer))]  
  81.         public IHttpActionResult DeleteCustomer(int id)  
  82.         {  
  83.             Customer customer = db.Customers.Find(id);  
  84.             if (customer == null)  
  85.             {  
  86.                 return NotFound();  
  87.             }  
  88.   
  89.             db.Customers.Remove(customer);  
  90.             db.SaveChanges();  
  91.   
  92.             return Ok(customer);  
  93.         }  
  94.         //GetCustomerByCountry returns list of nb customers by country   
  95.        [Route("Customers/GetCustomerByCountry")]  
  96.         public IList<CustomerData> GetCustomerByCountry()  
  97.         {  
  98.             List<string> countryList = new List<string>() { "Morocco""India""USA""Spain" };  
  99.             IEnumerable<Customer> customerList = db.Customers;  
  100.             List <CustomerData> result = new List<CustomerData>();  
  101.   
  102.             foreach (var item in countryList)  
  103.             {  
  104.                 int nbCustomer = customerList.Where(c => c.Country == item).Count();  
  105.                 result.Add(new CustomerData()  
  106.                 {  
  107.                     CountryName = item,  
  108.                     value = nbCustomer  
  109.                 });  
  110.             }  
  111.   
  112.             if(result != null)  
  113.             {  
  114.                 return result;  
  115.             }  
  116.   
  117.             return null;  
  118.   
  119.   
  120.   
  121.         }  
  122.   
  123.         protected override void Dispose(bool disposing)  
  124.         {  
  125.             if (disposing)  
  126.             {  
  127.                 db.Dispose();  
  128.             }  
  129.             base.Dispose(disposing);  
  130.         }  
  131.   
  132.         private bool CustomerExists(int id)  
  133.         {  
  134.             return db.Customers.Count(e => e.CustID == id) > 0;  
  135.         }  
  136.     }  
  137. }   

Calling Services using Knockout.js library

First of all, we are installing knockout.js library. From solution explorer panel, right click on references > Manage NuGet Packages…


Next, type Knockout.js in search text box, select the first line as below, and click on Install button.


Now, we need to add new js file. Right click on scripts folder > Add > JavaScript File.


App.js

Here, we create our View Model that contains all the business logic, and then, we bind it with ko.applyBindings(new viewModel()) which is enabled to activate knockout for the current HTML document.

As you can see in the below code, ko provides observables to bind to the Model.

  • observable() is used to define Model properties which can notify the changes and update the Model automatically.
  • observableArray([]) is used to bind list of elements.
    1. var ViewModel = function () {  
    2.   
    3.     var self = this;  
    4.     self.CustID = ko.observable();  
    5.     self.FirstName = ko.observable();  
    6.     self.LastName = ko.observable();  
    7.     self.Email = ko.observable();  
    8.     self.CountryList = ko.observableArray(['Morocco''India''USA''Spain']);  
    9.     self.Country = ko.observable();  
    10.   
    11.     self.customerList = ko.observableArray([]);  
    12.   
    13.     var CustomerUri = '/api/Customers/';  
    14.   
    15.       
    16.   
    17.     function ajaxFunction(uri, method, data) {  
    18.   
    19.         //self.errorMessage('');  
    20.   
    21.         return $.ajax({  
    22.   
    23.             type method,  
    24.             url uri,  
    25.             dataType 'json',  
    26.             contentType 'application/json',  
    27.             data data ? JSON.stringify(data)  null  
    28.   
    29.         }).fail(function (jqXHR, textStatus, errorThrown) {  
    30.             alert('Error  ' + errorThrown);  
    31.         });  
    32.     }  
    33.   
    34.   
    35.     // Clear Fields  
    36.     self.clearFields = function clearFields() {  
    37.         self.FirstName('');  
    38.         self.LastName('');  
    39.         self.Email('');  
    40.         self.Country('');  
    41.     }  
    42.   
    43.     //Add new Customer  
    44.     self.addNewCustomer = function addNewCustomer(newCustomer) {  
    45.   
    46.         var CustObject = {  
    47.             CustID self.CustID(),  
    48.             FirstName: self.FirstName(),  
    49.             LastName self.LastName(),  
    50.             Email self.Email(),  
    51.             Country self.Country()  
    52.         };  
    53.         ajaxFunction(CustomerUri, 'POST', CustObject).done(function () {  
    54.   
    55.             self.clearFields();  
    56.             alert('Customer Added Successfully !');  
    57.             getCustomerList()  
    58.         });  
    59.     }  
    60.   
    61.     //Get Customer List  
    62.     function getCustomerList() {  
    63.         $("div.loadingZone").show();  
    64.         ajaxFunction(CustomerUri, 'GET').done(function (data) {  
    65.             $("div.loadingZone").hide();  
    66.             self.customerList(data);  
    67.         });  
    68.   
    69.     }  
    70.   
    71.     //Get Detail Customer  
    72.     self.detailCustomer = function (selectedCustomer) {  
    73.   
    74.         self.CustID(selectedCustomer.CustID);  
    75.         self.FirstName(selectedCustomer.FirstName);  
    76.         self.LastName(selectedCustomer.LastName);  
    77.         self.Email(selectedCustomer.Email);  
    78.         self.Country(selectedCustomer.Country);  
    79.   
    80.         $('#Save').hide();  
    81.         $('#Clear').hide();  
    82.   
    83.         $('#Update').show();  
    84.         $('#Cancel').show();  
    85.   
    86.     };  
    87.   
    88.     self.cancel = function () {  
    89.   
    90.         self.clearFields();  
    91.   
    92.         $('#Save').show();  
    93.         $('#Clear').show();  
    94.   
    95.         $('#Update').hide();  
    96.         $('#Cancel').hide();  
    97.     }  
    98.   
    99.     //Update Customer  
    100.     self.updateCustomer = function () {  
    101.   
    102.         var CustObject = {  
    103.             CustID self.CustID(),  
    104.             FirstName self.FirstName(),  
    105.             LastName self.LastName(),  
    106.             Email self.Email(),  
    107.             Country self.Country()  
    108.         };  
    109.   
    110.         ajaxFunction(CustomerUri + self.CustID(), 'PUT', CustObject).done(function () {  
    111.             alert('Customer Updated Successfully !');  
    112.             getCustomerList();  
    113.             self.cancel();  
    114.         });  
    115.     }  
    116.   
    117.     //Delete Customer  
    118.     self.deleteCustomer = function (customer) {  
    119.   
    120.         ajaxFunction(CustomerUri + customer.CustID, 'DELETE').done(function () {  
    121.   
    122.             alert('Customer Deleted Successfully');  
    123.             getCustomerList();  
    124.         })  
    125.   
    126.     }  
    127.   
    128.     //Chart Line function used to display a chart which represents nb of customers by country  
    129.     function chartLine() {  
    130.   
    131.         ajaxFunction('http//localhost50706/Customers/GetCustomerByCountry''GET').done(function (result) {  
    132.             console.log(result);  
    133.             Morris.Line({  
    134.                 element 'line-chart',  
    135.                 data result,  
    136.                 xkey 'CountryName',  
    137.                 // A list of names of data record attributes that contain y-values.  
    138.                 ykeys ['value'],  
    139.                 // Labels for the ykeys -- will be displayed when you hover over the  
    140.                 // chart.  
    141.                 labels ['Value'],  
    142.   
    143.                 parseTime false  
    144.             });  
    145.   
    146.   
    147.         });  
    148.   
    149.     };  
    150.   
    151.     chartLine();  
    152.     getCustomerList();  
    153.   
    154. };  
    155.   
    156. ko.applyBindings(new ViewModel());  

Now, from Solution Explorer panel, we are going to add index.html file as shown below.


Index.html 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.   
  5.     <meta charset="utf-8">  
  6.     <meta http-equiv="X-UA-Compatible" content="IE=edge">  
  7.     <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.   
  9.     <title>. Customer App . Web API2 Á KnockOutJS</title>  
  10.     <meta charset="utf-8" />  
  11.   
  12.     <!-- CSS -->  
  13.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  14.     <link href="https//cdn.oesmith.co.uk/morris-0.5.1.css" rel="stylesheet" />  
  15.       
  16.     
  17.   
  18. </head>  
  19. <body>  
  20.   
  21.     <nav class="navbar navbar-default navbar-fixed-top">  
  22.   
  23.         <div class="container-fluid">  
  24.   
  25.             <div class="navbar-header">  
  26.                 <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">  
  27.                     <span class="sr-only">Toggle navigation</span>  
  28.                     <span class="icon-bar"></span>  
  29.                     <span class="icon-bar"></span>  
  30.                     <span class="icon-bar"></span>  
  31.                 </button>  
  32.                 <a class="navbar-brand" href="#">WEB API2 - KnockOutJS</a>  
  33.             </div> <!-- END HEADER NAV -->  
  34.   
  35.         </div> <!-- END CONTAINER -->  
  36.   
  37.     </nav><!-- END NAV-->  
  38.   
  39.     <div class="container" style="margin-top 7%;">  
  40.   
  41.   
  42.         <div class="row">  
  43.   
  44.             <div class="col-md-4">  
  45.   
  46.                 <!-- FORM -->  
  47.                 <div class="panel panel-default">  
  48.   
  49.                     <div class="panel-heading"> <span class="glyphicon glyphicon glyphicon-tag" aria-hidden="true"></span> <b>Add New Customer</b></div>  
  50.                     <div class="panel-body">  
  51.   
  52.                         <form>  
  53.   
  54.                             <div class="form-group" style="displaynone;">  
  55.                                 <label for="CustomerID">Customer ID</label>  
  56.                                 <input type="text" id="CustomerID" class="form-control" data-bind="valueCustID" placeholder="Customer ID" />  
  57.                             </div><!-- END CUSTOMER ID -->  
  58.   
  59.                             <div class="form-group">  
  60.                                 <label for="FirstName">First Name</label>  
  61.                                 <input type="text" id="FirstName" class="form-control" data-bind="valueFirstName" placeholder="First Name" />  
  62.                             </div><!-- END FIRST NAME -->  
  63.   
  64.                             <div class="form-group">  
  65.                                 <label for="LastName">Last Name</label>  
  66.                                 <input type="text" id="LastName" class="form-control" data-bind="value LastName" placeholder="Last Name" />  
  67.                             </div><!-- END LAST NAME -->  
  68.   
  69.                             <div class="form-group">  
  70.                                 <label for="Email">Email</label>  
  71.                                 <input type="email" id="Email" class="form-control" data-bind="value Email" placeholder="Email" />  
  72.                             </div> <!-- END EMAIL -->  
  73.   
  74.                             <div class="form-group">  
  75.                                 <label for="Country">Country</label>  
  76.                                 <select class="form-control" data-bind="options CountryList, value Country, optionsCaption 'Select your Country ...' " ></select>  
  77.                             </div> <!-- END COUNTRY -->  
  78.   
  79.   
  80.                             <button type="button" class="btn btn-success" data-bind="click addNewCustomer" id="Save">  
  81.                                 <span class="glyphicon  glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save  
  82.                             </button>  
  83.   
  84.                             <button type="button" class="btn btn-info" data-bind="click clearFields" id="Clear">  
  85.                                 <span class="glyphicon  glyphicon glyphicon-refresh" aria-hidden="true"></span> Clear  
  86.                             </button>  
  87.   
  88.                             <button type="button" class="btn btn-warning" data-bind="clickupdateCustomer " style="display:none;" id="Update">  
  89.                                 <span class="glyphicon  glyphicon glyphicon-pencil" aria-hidden="true"></span> Update Customer  
  90.                             </button>  
  91.   
  92.                             <button type="button" class="btn btn-default" data-bind="clickcancel " style="displaynone;" id="Cancel">  
  93.                                 <span class="glyphicon  glyphicon glyphicon-remove" aria-hidden="true"></span> Cancel  
  94.                             </button>  
  95.   
  96.                         </form> <!-- END FORM -->  
  97.   
  98.   
  99.                     </div> <!-- END PANEL BODY-->  
  100.   
  101.                 </div><!-- END PANEL-->  
  102.   
  103.             </div> <!-- END  col-md-4 -->  
  104.   
  105.             <div class="col-md-8">  
  106.   
  107.                 <div class="panel panel-default">  
  108.   
  109.                     <div class="panel-heading"><span class="glyphicon  glyphicon glyphicon-stats" aria-hidden="true"></span><b> Charting Customer</b>   </div>  
  110.   
  111.                     <div class="panel-body">  
  112.   
  113.   
  114.                         <!-- <img src="images/Chart.png" style="width60%; margin6px 70px;" /> -->  
  115.   
  116.                         <div id="line-chart" style="height 300px;"></div><br/><br/>  
  117.   
  118.                     </div> <!-- END PANEL-BODY-->  
  119.   
  120.                 </div> <!-- END PANEL-->  
  121.   
  122.             </div> <!-- END col-md-8-->  
  123.   
  124.         </div>  
  125.   
  126.         <div class="row">  
  127.   
  128.             <div class="col-md-12">  
  129.   
  130.                 <div class="panel panel-default">  
  131.   
  132.                     <div class="panel-heading">  
  133.                         <span class="glyphicon  glyphicon glyphicon-zoom-in" aria-hidden="true"></span>  <b>Customer List </b>  
  134.                         <div class="loadingZone" style="color #000; displayblock; floatright; displaynone;"> <img src="images/ajax-loader.gif" /> Refresh Data ...</div>  
  135.                     </div>  
  136.   
  137.                     <div class="panel-body">  
  138.   
  139.                         <table class="table table-hover">  
  140.   
  141.                             <thead>  
  142.                                 <tr>  
  143.                                     <th><span class="glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span></th>  
  144.                                     <th>#</th>  
  145.                                     <th>First Name</th>  
  146.                                     <th>Last Name</th>  
  147.                                     <th>Email</th>  
  148.                                     <th>Country</th>  
  149.                                     <th></th>  
  150.                                 </tr>  
  151.                             </thead> <!-- END THEAD -->  
  152.   
  153.                             <tbody data-bind="foreach customerList">  
  154.   
  155.                                 <tr>  
  156.   
  157.                                     <td> <button type="button" class="btn btn-default btn-xs" data-bind="click $root.detailCustomer"> <span class="glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span></button> </td>  
  158.                                     <td> <span data-bind="text CustID"></span> </td>  
  159.                                     <td> <span data-bind="text FirstName"></span></td>  
  160.                                     <td> <span data-bind="text LastName"></span></td>  
  161.                                     <td> <span data-bind="text Email"></span> </td>  
  162.                                     <td> <span data-bind="text Country"></span> </td>  
  163.   
  164.                                     <td>  
  165.   
  166.                                         <button type="button" class="btn btn-danger btn-xs">  
  167.                                             <span class="glyphicon glyphicon glyphicon-trash" aria-hidden="true" data-bind="click $root.deleteCustomer"></span>  
  168.                                         </button>  
  169.                                     </td>  
  170.   
  171.                                 </tr>  
  172.   
  173.                                   
  174.   
  175.                             </tbody> <!-- END TBODY -->  
  176.   
  177.                         </table> <!-- END TABLE -->  
  178.   
  179.   
  180.                     </div>  
  181.   
  182.                 </div>  
  183.   
  184.             </div>  
  185.   
  186.         </div>  
  187.     </div> <!-- END CONTAINER-->  
  188.   
  189.     <!-- JS -->  
  190.     <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->  
  191.     <script src="Scripts/jquery-1.10.2.min.js"></script>  
  192.     <!-- Include all compiled plugins (below), or include individual files as needed -->  
  193.     <script src="Scripts/bootstrap.min.js"></script>  
  194.     <script src="Scripts/knockout-3.4.0.js"></script>  
  195.   
  196.     <script src="https//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>  
  197.     <script src="https//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>  
  198.     <!-- app.js-->  
  199.     <script src="Scripts/app.js"></script>  
  200.      
  201. </body>  
  202. </html>   

In order to exchange the data between HTML page and JavaScript file, knockout.js offers various types of bindings that should be used within data-bind attribute.

  • Click represents a click event handler to call JavaScript function.
  • Value represents the value binding with UI element’s to the property defined into view Model.
  • Text represents the text value to the UI element.
  • Foreach used to fetch an array.

Now, you can run your application. Don’t forget to change the URL address as below.

http//localhost55192/index.html

Let’s see the output.




That’s all, Please send your feedback and queries in comments box.

Up Next
    Ebook Download
    View all
    Learn
    View all