Introduction
In this post, I will show you how to create master details, which are based on knockout.js library, using ASP.NET Web API 2 and Entity Framework.
Prerequisites
As I said before, to achieve our requirement, we must have Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.
In this article, we are going to:
- Create a database.
- Create Web API Application.
- Configuring Entity Framework ORM.
- Implementing http Services, which should be used.
- Using knockout.js library for calling Services.
SQL database part
Here, you will find the scripts to create database and tables.
Create database
- USE [master]
- GO
- /****** Object: Database [CompanyDB] Script Date: 3/11/2017 8:18:51 AM ******/
- CREATE DATABASE [CompanyDB]
- CONTAINMENT = NONE
- ON PRIMARY
- ( NAME = N'CompanyDB', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CompanyDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
- LOG ON
- ( NAME = N'CompanyDB_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CompanyDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
- GO
- ALTER DATABASE [CompanyDB] SET COMPATIBILITY_LEVEL = 110
- GO
- IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
- begin
- EXEC [CompanyDB].[dbo].[sp_fulltext_database] @action = 'enable'
- end
- GO
- ALTER DATABASE [CompanyDB] SET ANSI_NULL_DEFAULT OFF
- GO
- ALTER DATABASE [CompanyDB] SET ANSI_NULLS OFF
- GO
- ALTER DATABASE [CompanyDB] SET ANSI_PADDING OFF
- GO
- ALTER DATABASE [CompanyDB] SET ANSI_WARNINGS OFF
- GO
- ALTER DATABASE [CompanyDB] SET ARITHABORT OFF
- GO
- ALTER DATABASE [CompanyDB] SET AUTO_CLOSE OFF
- GO
- ALTER DATABASE [CompanyDB] SET AUTO_CREATE_STATISTICS ON
- GO
- ALTER DATABASE [CompanyDB] SET AUTO_SHRINK OFF
- GO
- ALTER DATABASE [CompanyDB] SET AUTO_UPDATE_STATISTICS ON
- GO
- ALTER DATABASE [CompanyDB] SET CURSOR_CLOSE_ON_COMMIT OFF
- GO
- ALTER DATABASE [CompanyDB] SET CURSOR_DEFAULT GLOBAL
- GO
- ALTER DATABASE [CompanyDB] SET CONCAT_NULL_YIELDS_NULL OFF
- GO
- ALTER DATABASE [CompanyDB] SET NUMERIC_ROUNDABORT OFF
- GO
- ALTER DATABASE [CompanyDB] SET QUOTED_IDENTIFIER OFF
- GO
- ALTER DATABASE [CompanyDB] SET RECURSIVE_TRIGGERS OFF
- GO
- ALTER DATABASE [CompanyDB] SET DISABLE_BROKER
- GO
- ALTER DATABASE [CompanyDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
- GO
- ALTER DATABASE [CompanyDB] SET DATE_CORRELATION_OPTIMIZATION OFF
- GO
- ALTER DATABASE [CompanyDB] SET TRUSTWORTHY OFF
- GO
- ALTER DATABASE [CompanyDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
- GO
- ALTER DATABASE [CompanyDB] SET PARAMETERIZATION SIMPLE
- GO
- ALTER DATABASE [CompanyDB] SET READ_COMMITTED_SNAPSHOT OFF
- GO
- ALTER DATABASE [CompanyDB] SET HONOR_BROKER_PRIORITY OFF
- GO
- ALTER DATABASE [CompanyDB] SET RECOVERY SIMPLE
- GO
- ALTER DATABASE [CompanyDB] SET MULTI_USER
- GO
- ALTER DATABASE [CompanyDB] SET PAGE_VERIFY CHECKSUM
- GO
- ALTER DATABASE [CompanyDB] SET DB_CHAINING OFF
- GO
- ALTER DATABASE [CompanyDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
- GO
- ALTER DATABASE [CompanyDB] SET TARGET_RECOVERY_TIME = 0 SECONDS
- GO
- ALTER DATABASE [CompanyDB] SET READ_WRITE
- GO
Create tables
Here, we need to create 2 tables respectively, namely Customers and Orders.
- USE [CompanyDB]
- GO
- /****** Object: Table [dbo].[Customers] Script Date: 3/11/2017 8:19:22 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE [dbo].[Customers](
- [CustomerID] [varchar](50) NOT NULL,
- [CompanyName] [varchar](50) NULL,
- [ContactName] [varchar](50) NULL,
- [ContactTitle] [varchar](50) NULL,
- [City] [varchar](50) NULL,
- [Country] [varchar](50) NULL,
- CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
- (
- [CustomerID] 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
- USE [CompanyDB]
- GO
- /****** Object: Table [dbo].[Orders] Script Date: 3/11/2017 8:19:38 AM ******/
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE [dbo].[Orders](
- [OrderID] [int] NOT NULL,
- [CustomerID] [varchar](50) NOT NULL,
- [EmployeeID] [int] NULL,
- [OrderDate] [date] NULL,
- [RequiredDate] [date] NULL,
- [ShippedDate] [date] NULL,
- [ShipName] [varchar](50) NULL,
- CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED
- (
- [OrderID] 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
After creating the tables, you can add some records, as shown below for the demo.
Customer table

Order table

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.

Now, a new dialog will pop up to select the template. We are going to 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 this, right click on the project name, click Add > Add New Item. Dialog box will pop up, inside Visual C#, select Data, followed by ADO.NET Entity Data Model and enter name for your Dbcontext model as CompanyModel and finally click Add.

At this stage, we are going to choose EF Designer from the database, as shown below.

In this snapshot given below, we need to select your Server name, then via dropdown list in connect to a database section, you should choose your database name. Finally, click OK button.


In the next step, the dialog Entity Data Model wizard will pop up to choose the objects which we want to use. In this example, we are going to choose Customers and Orders tables and click Finish button.
Finally, we will see that EDMX model generates Customer and Order entities.


Create a controller
Now, we are going to create a controller. Right click on the controllers folder > Add > Controller> select Web API 2 Controller – Empty > click Add.

Enter Controller name (‘CompanyController’).

CompanyController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- namespace MasterDetail.Controllers
- {
- [RoutePrefix("api/Company")]
- public class CompanyController : ApiController
- {
- //DbContext
- private CompanyDBEntities db = new CompanyDBEntities();
- public IQueryable<Customer> GetCustomers()
- {
- return db.Customers;
- }
- [Route("{customerId}")]
- public IQueryable<Order> GetOrdersByCustomer(string customerId)
- {
- return db.Orders.Where(o => o.CustomerID == customerId).AsQueryable();
- }
- }
- }
As you can see, there are two methods given above, the first thing is used to get all the customers and the second method returns orders related to the customer Id given as a parameter.
Now, we need to add new js file. Right click on scripts folder > Add > JavaScript file.

App.js
- var viewModel = function() {
- var self = this;
- self.CustomerID = ko.observable();
- self.CompanyName = ko.observable();
- self.ContactName = ko.observable();
- self.ContactTitle = ko.observable();
- self.City = ko.observable();
- self.Country = ko.observable();
- self.customerList = ko.observableArray([]);
- self.OrderID = ko.observable();
- self.EmployeeID = ko.observable();
- self.OrderDate = ko.observable();
- self.RequiredDate = ko.observable();
- self.ShippedDate = ko.observable();
- self.ShipName = ko.observable();
- self.OrdersList = ko.observableArray([]);
- var CompanyUri = '/api/Company/';
- 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);
- });
- }
- //Customer List function which returns all customers from database.
- function customerList() {
- ajaxFunction(CompanyUri, 'GET').done(function (data) {
- self.customerList(data);
- });
- }
- //Detail Orders function accepts customer id as parameter and returns all orders related to customer id.
- self.detailOrders = function(customer) {
- ajaxFunction(CompanyUri + customer.CustomerID, 'GET').done(function (data) {
- self.OrdersList(data);
- });
- }
- customerList();
- };
- ko.applyBindings(new viewModel());
Now, from solution explorer panel, we are going to add MasterDetails.html file.

MasterDetails.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>Master Detail :: Template</title>
- <meta charset="utf-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <!--CSS-->
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- </head>
- <body>
- <nav class="navbar navbar-default navbar-fixed-top">
- <div class="container-fluid">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
- <span class="sr-only">Toggle navigation</span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- <a class="navbar-brand" href="#">Matser Detail - KnockOutJS</a>
- </div> <!-- END HEADER NAV -->
- </div> <!-- END CONTAINER -->
- </nav><!-- END NAV-->
- <div class="container" style="margin-top: 7%;">
- <div class="row">
- <div class="col-md-9">
- <!-- FORM -->
- <div class="panel panel-default">
- <div class="panel-heading"> <span class="glyphicon glyphicon glyphicon-tag" aria-hidden="true"></span> <b>Customer List </b></div>
- <div class="panel-body">
- <table class="table table-hover">
- <thead>
- <tr>
- <th><span class="glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span></th>
- <th>Customer ID</th>
- <th>Company Name</th>
- <th>Contact Name</th>
- <th>Contact Title</th>
- <th>City</th>
- <th>Country</th>
- </tr>
- </thead> <!-- END THEAD -->
- <tbody data-bind="foreach: customerList">
- <tr>
- <td> <button type="button" class="btn btn-default btn-xs" data-bind="click: $root.detailOrders"> <span class="glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span></button> </td>
- <td> <span data-bind="text: CustomerID"></span> </td>
- <td> <span data-bind="text: CompanyName"></span> </td>
- <td> <span data-bind="text: ContactName"></span> </td>
- <td> <span data-bind="text: ContactTitle"></span> </td>
- <td> <span data-bind="text: City"></span> </td>
- <td> <span data-bind="text: Country"></span> </td>
- </tr>
- </tbody> <!-- END TBODY -->
- </table> <!-- END TABLE -->
- </div> <!-- END PANEL BODY-->
- </div><!-- END PANEL-->
- </div> <!-- END col-md-8 -->
- </div> <!-- END ROW-->
- <div class="row">
- <div class="col-md-10">
- <!-- FORM -->
- <div class="panel panel-default">
- <div class="panel-heading"> <span class="glyphicon glyphicon glyphicon-tag" aria-hidden="true"></span> <b>Orders by Customer </b></div>
- <div class="panel-body">
- <table class="table table-hover">
- <thead>
- <tr>
- <th>OrderID</th>
- <th>Customer ID</th>
- <th>Employee ID</th>
- <th>Order Date</th>
- <th>Required Date</th>
- <th>Shipped Date</th>
- <th>Ship Name</th>
- </tr>
- </thead> <!-- END THEAD -->
- <tbody data-bind="foreach: OrdersList">
- <tr>
- <td> <span data-bind="text: OrderID"></span> </td>
- <td> <span data-bind="text: CustomerID"></span> </td>
- <td> <span data-bind="text: EmployeeID"></span> </td>
- <td> <span data-bind="text: OrderDate"></span> </td>
- <td> <span data-bind="text: RequiredDate"></span> </td>
- <td> <span data-bind="text: ShippedDate"></span> </td>
- <td> <span data-bind="text: ShipName"></span></td>
- </tr>
- </tbody>
- </table>
- </div> <!-- END PANEL BODY-->
- </div><!-- END PANEL-->
- </div> <!-- END col-md-10 -->
- </div> <!-- END ROW-->
- </div> <!-- END CONTAINER-->
- <!-- JS -->
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="Scripts/bootstrap.min.js"></script>
- <script src="Scripts/knockout-3.4.0.js"></script>
- <script src="Scripts/app.js"></script>
- </body>
- </html>
Note
Don’t forget to add knockout.js library.
<script src="Scripts/knockout-3.4.0.js"></script>
Output
Now, you can run your Application and let’s see the output.

Thiruppathi RPosted Mar 12, 2017, 10:52 PM
Nice Article For Knockout.js..