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.
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
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.
- var ViewModel = function () {
-
- var self = this;
- self.CustID = ko.observable();
- self.FirstName = ko.observable();
- self.LastName = ko.observable();
- self.Email = ko.observable();
- self.CountryList = ko.observableArray(['Morocco', 'India', 'USA', 'Spain']);
- self.Country = ko.observable();
-
- self.customerList = ko.observableArray([]);
-
- var CustomerUri = '/api/Customers/';
-
-
-
- function ajaxFunction(uri, method, data) {
-
-
-
- return $.ajax({
-
- type method,
- url uri,
- dataType 'json',
- contentType 'application/json',
- data data ? JSON.stringify(data) null
-
- }).fail(function (jqXHR, textStatus, errorThrown) {
- alert('Error ' + errorThrown);
- });
- }
-
-
-
- self.clearFields = function clearFields() {
- self.FirstName('');
- self.LastName('');
- self.Email('');
- self.Country('');
- }
-
-
- self.addNewCustomer = function addNewCustomer(newCustomer) {
-
- var CustObject = {
- CustID self.CustID(),
- FirstName: self.FirstName(),
- LastName self.LastName(),
- Email self.Email(),
- Country self.Country()
- };
- ajaxFunction(CustomerUri, 'POST', CustObject).done(function () {
-
- self.clearFields();
- alert('Customer Added Successfully !');
- getCustomerList()
- });
- }
-
-
- function getCustomerList() {
- $("div.loadingZone").show();
- ajaxFunction(CustomerUri, 'GET').done(function (data) {
- $("div.loadingZone").hide();
- self.customerList(data);
- });
-
- }
-
-
- self.detailCustomer = function (selectedCustomer) {
-
- self.CustID(selectedCustomer.CustID);
- self.FirstName(selectedCustomer.FirstName);
- self.LastName(selectedCustomer.LastName);
- self.Email(selectedCustomer.Email);
- self.Country(selectedCustomer.Country);
-
- $('#Save').hide();
- $('#Clear').hide();
-
- $('#Update').show();
- $('#Cancel').show();
-
- };
-
- self.cancel = function () {
-
- self.clearFields();
-
- $('#Save').show();
- $('#Clear').show();
-
- $('#Update').hide();
- $('#Cancel').hide();
- }
-
-
- self.updateCustomer = function () {
-
- var CustObject = {
- CustID self.CustID(),
- FirstName self.FirstName(),
- LastName self.LastName(),
- Email self.Email(),
- Country self.Country()
- };
-
- ajaxFunction(CustomerUri + self.CustID(), 'PUT', CustObject).done(function () {
- alert('Customer Updated Successfully !');
- getCustomerList();
- self.cancel();
- });
- }
-
-
- self.deleteCustomer = function (customer) {
-
- ajaxFunction(CustomerUri + customer.CustID, 'DELETE').done(function () {
-
- alert('Customer Deleted Successfully');
- getCustomerList();
- })
-
- }
-
-
- function chartLine() {
-
- ajaxFunction('http//localhost50706/Customers/GetCustomerByCountry', 'GET').done(function (result) {
- console.log(result);
- Morris.Line({
- element 'line-chart',
- data result,
- xkey 'CountryName',
-
- ykeys ['value'],
-
-
- labels ['Value'],
-
- parseTime false
- });
-
-
- });
-
- };
-
- chartLine();
- getCustomerList();
-
- };
-
- ko.applyBindings(new ViewModel());
Now, from Solution Explorer panel, we are going to add index.html file as shown below.
Index.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.