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.
- Create Database
- USE [master]
- GO
- /****** Object Database [DBCustomer] Script Date 3/4/2017 32357 PM ******/
- CREATE DATABASE [DBCustomer]
- CONTAINMENT = NONE
- ON PRIMARY
- ( NAME = N'DBCustomer', FILENAME = N'c\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBCustomer.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
- LOG ON
- ( 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%)
- GO
- ALTER DATABASE [DBCustomer] SET COMPATIBILITY_LEVEL = 110
- GO
- IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
- begin
- EXEC [DBCustomer].[dbo].[sp_fulltext_database] @action = 'enable'
- end
- GO
- ALTER DATABASE [DBCustomer] SET ANSI_NULL_DEFAULT OFF
- GO
- ALTER DATABASE [DBCustomer] SET ANSI_NULLS OFF
- GO
- ALTER DATABASE [DBCustomer] SET ANSI_PADDING OFF
- GO
- ALTER DATABASE [DBCustomer] SET ANSI_WARNINGS OFF
- GO
- ALTER DATABASE [DBCustomer] SET ARITHABORT OFF
- GO
- ALTER DATABASE [DBCustomer] SET AUTO_CLOSE OFF
- GO
- ALTER DATABASE [DBCustomer] SET AUTO_CREATE_STATISTICS ON
- GO
- ALTER DATABASE [DBCustomer] SET AUTO_SHRINK OFF
- GO
- ALTER DATABASE [DBCustomer] SET AUTO_UPDATE_STATISTICS ON
- GO
- ALTER DATABASE [DBCustomer] SET CURSOR_CLOSE_ON_COMMIT OFF
- GO
- ALTER DATABASE [DBCustomer] SET CURSOR_DEFAULT GLOBAL
- GO
- ALTER DATABASE [DBCustomer] SET CONCAT_NULL_YIELDS_NULL OFF
- GO
- ALTER DATABASE [DBCustomer] SET NUMERIC_ROUNDABORT OFF
- GO
- ALTER DATABASE [DBCustomer] SET QUOTED_IDENTIFIER OFF
- GO
- ALTER DATABASE [DBCustomer] SET RECURSIVE_TRIGGERS OFF
- GO
- ALTER DATABASE [DBCustomer] SET DISABLE_BROKER
- GO
- ALTER DATABASE [DBCustomer] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
- GO
- ALTER DATABASE [DBCustomer] SET DATE_CORRELATION_OPTIMIZATION OFF
- GO
- ALTER DATABASE [DBCustomer] SET TRUSTWORTHY OFF
- GO
- ALTER DATABASE [DBCustomer] SET ALLOW_SNAPSHOT_ISOLATION OFF
- GO
- ALTER DATABASE [DBCustomer] SET PARAMETERIZATION SIMPLE
- GO
- ALTER DATABASE [DBCustomer] SET READ_COMMITTED_SNAPSHOT OFF
- GO
- ALTER DATABASE [DBCustomer] SET HONOR_BROKER_PRIORITY OFF
- GO
- ALTER DATABASE [DBCustomer] SET RECOVERY SIMPLE
- GO
- ALTER DATABASE [DBCustomer] SET MULTI_USER
- GO
- ALTER DATABASE [DBCustomer] SET PAGE_VERIFY CHECKSUM
- GO
- ALTER DATABASE [DBCustomer] SET DB_CHAINING OFF
- GO
- ALTER DATABASE [DBCustomer] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
- GO
- ALTER DATABASE [DBCustomer] SET TARGET_RECOVERY_TIME = 0 SECONDS
- GO
- ALTER DATABASE [DBCustomer] SET READ_WRITE
- GO
- Create Table
- USE [DBCustomer]
- GO
- /****** Object Table [dbo].[Customer] Script Date 3/4/2017 32449 PM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE [dbo].[Customer](
- [CustID] [int] IDENTITY(1,1) NOT NULL,
- [FirstName] [varchar](50) NULL,
- [LastName] [varchar](50) NULL,
- [Email] [varchar](50) NULL,
- [Country] [varchar](50) NULL,
- CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
- (
- [CustID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
- GO
- SET ANSI_PADDING OFF
- 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.

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.


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
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Web.Http.Description;
- using CustomerApp;
- using CustomerApp.Models;
- namespace CustomerApp.Controllers
- {
- public class CustomersController ApiController
- {
- //DbContext
- private DBCustomerEntities db = new DBCustomerEntities();
- // GET api/Customers
- public IQueryable<Customer> GetCustomers()
- {
- return db.Customers;
- }
- // PUT api/Customers/5
- [ResponseType(typeof(void))]
- public IHttpActionResult PutCustomer(int id, Customer customer)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- if (id != customer.CustID)
- {
- return BadRequest();
- }
- db.Entry(customer).State = EntityState.Modified;
- try
- {
- db.SaveChanges();
- }
- catch (DbUpdateConcurrencyException)
- {
- if (!CustomerExists(id))
- {
- return NotFound();
- }
- else
- {
- throw;
- }
- }
- return StatusCode(HttpStatusCode.NoContent);
- }
- // POST api/Customers
- [ResponseType(typeof(Customer))]
- public IHttpActionResult PostCustomer(Customer customer)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- db.Customers.Add(customer);
- db.SaveChanges();
- return CreatedAtRoute("DefaultApi", new { id = customer.CustID }, customer);
- }
- // DELETE api/Customers/5
- [ResponseType(typeof(Customer))]
- public IHttpActionResult DeleteCustomer(int id)
- {
- Customer customer = db.Customers.Find(id);
- if (customer == null)
- {
- return NotFound();
- }
- db.Customers.Remove(customer);
- db.SaveChanges();
- return Ok(customer);
- }
- //GetCustomerByCountry returns list of nb customers by country
- [Route("Customers/GetCustomerByCountry")]
- public IList<CustomerData> GetCustomerByCountry()
- {
- List<string> countryList = new List<string>() { "Morocco", "India", "USA", "Spain" };
- IEnumerable<Customer> customerList = db.Customers;
- List <CustomerData> result = new List<CustomerData>();
- foreach (var item in countryList)
- {
- int nbCustomer = customerList.Where(c => c.Country == item).Count();
- result.Add(new CustomerData()
- {
- CountryName = item,
- value = nbCustomer
- });
- }
- if(result != null)
- {
- return result;
- }
- return null;
- }
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- db.Dispose();
- }
- base.Dispose(disposing);
- }
- private bool CustomerExists(int id)
- {
- return db.Customers.Count(e => e.CustID == id) > 0;
- }
- }
- }
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…






Ravi KandelPosted Mar 8, 2017, 8:24 AM
Awesome Thanks for sharing
richard griffithsPosted Mar 8, 2017, 6:45 AM
Excellent article - are you able to supply sample code/app - thanks