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

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,

SQL Database part

Here, find the script to create database and table.

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

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

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

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.

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

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.