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:

SQL database part

Here, you will find the scripts to create database and tables.

Create database

  1. USE [master]
  2. GO
  3. /****** Object: Database [CompanyDB] Script Date: 3/11/2017 8:18:51 AM ******/
  4. CREATE DATABASE [CompanyDB]
  5. CONTAINMENT = NONE
  6. ON PRIMARY
  7. ( NAME = N'CompanyDB', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\CompanyDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
  8. LOG ON
  9. ( 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%)
  10. GO
  11. ALTER DATABASE [CompanyDB] SET COMPATIBILITY_LEVEL = 110
  12. GO
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
  14. begin
  15. EXEC [CompanyDB].[dbo].[sp_fulltext_database] @action = 'enable'
  16. end
  17. GO
  18. ALTER DATABASE [CompanyDB] SET ANSI_NULL_DEFAULT OFF
  19. GO
  20. ALTER DATABASE [CompanyDB] SET ANSI_NULLS OFF
  21. GO
  22. ALTER DATABASE [CompanyDB] SET ANSI_PADDING OFF
  23. GO
  24. ALTER DATABASE [CompanyDB] SET ANSI_WARNINGS OFF
  25. GO
  26. ALTER DATABASE [CompanyDB] SET ARITHABORT OFF
  27. GO
  28. ALTER DATABASE [CompanyDB] SET AUTO_CLOSE OFF
  29. GO
  30. ALTER DATABASE [CompanyDB] SET AUTO_CREATE_STATISTICS ON
  31. GO
  32. ALTER DATABASE [CompanyDB] SET AUTO_SHRINK OFF
  33. GO
  34. ALTER DATABASE [CompanyDB] SET AUTO_UPDATE_STATISTICS ON
  35. GO
  36. ALTER DATABASE [CompanyDB] SET CURSOR_CLOSE_ON_COMMIT OFF
  37. GO
  38. ALTER DATABASE [CompanyDB] SET CURSOR_DEFAULT GLOBAL
  39. GO
  40. ALTER DATABASE [CompanyDB] SET CONCAT_NULL_YIELDS_NULL OFF
  41. GO
  42. ALTER DATABASE [CompanyDB] SET NUMERIC_ROUNDABORT OFF
  43. GO
  44. ALTER DATABASE [CompanyDB] SET QUOTED_IDENTIFIER OFF
  45. GO
  46. ALTER DATABASE [CompanyDB] SET RECURSIVE_TRIGGERS OFF
  47. GO
  48. ALTER DATABASE [CompanyDB] SET DISABLE_BROKER
  49. GO
  50. ALTER DATABASE [CompanyDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
  51. GO
  52. ALTER DATABASE [CompanyDB] SET DATE_CORRELATION_OPTIMIZATION OFF
  53. GO
  54. ALTER DATABASE [CompanyDB] SET TRUSTWORTHY OFF
  55. GO
  56. ALTER DATABASE [CompanyDB] SET ALLOW_SNAPSHOT_ISOLATION OFF
  57. GO
  58. ALTER DATABASE [CompanyDB] SET PARAMETERIZATION SIMPLE
  59. GO
  60. ALTER DATABASE [CompanyDB] SET READ_COMMITTED_SNAPSHOT OFF
  61. GO
  62. ALTER DATABASE [CompanyDB] SET HONOR_BROKER_PRIORITY OFF
  63. GO
  64. ALTER DATABASE [CompanyDB] SET RECOVERY SIMPLE
  65. GO
  66. ALTER DATABASE [CompanyDB] SET MULTI_USER
  67. GO
  68. ALTER DATABASE [CompanyDB] SET PAGE_VERIFY CHECKSUM
  69. GO
  70. ALTER DATABASE [CompanyDB] SET DB_CHAINING OFF
  71. GO
  72. ALTER DATABASE [CompanyDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
  73. GO
  74. ALTER DATABASE [CompanyDB] SET TARGET_RECOVERY_TIME = 0 SECONDS
  75. GO
  76. ALTER DATABASE [CompanyDB] SET READ_WRITE
  77. GO

Create tables

Here, we need to create 2 tables respectively, namely Customers and Orders.

  1. USE [CompanyDB]
  2. GO
  3. /****** Object: Table [dbo].[Customers] Script Date: 3/11/2017 8:19:22 AM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. SET ANSI_PADDING ON
  9. GO
  10. CREATE TABLE [dbo].[Customers](
  11. [CustomerID] [varchar](50) NOT NULL,
  12. [CompanyName] [varchar](50) NULL,
  13. [ContactName] [varchar](50) NULL,
  14. [ContactTitle] [varchar](50) NULL,
  15. [City] [varchar](50) NULL,
  16. [Country] [varchar](50) NULL,
  17. CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
  18. (
  19. [CustomerID] ASC
  20. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  21. ) ON [PRIMARY]
  22. GO
  23. SET ANSI_PADDING OFF
  24. GO
  25. USE [CompanyDB]
  26. GO
  27. /****** Object: Table [dbo].[Orders] Script Date: 3/11/2017 8:19:38 AM ******/
  28. SET ANSI_NULLS ON
  29. GO
  30. SET QUOTED_IDENTIFIER ON
  31. GO
  32. SET ANSI_PADDING ON
  33. GO
  34. CREATE TABLE [dbo].[Orders](
  35. [OrderID] [int] NOT NULL,
  36. [CustomerID] [varchar](50) NOT NULL,
  37. [EmployeeID] [int] NULL,
  38. [OrderDate] [date] NULL,
  39. [RequiredDate] [date] NULL,
  40. [ShippedDate] [date] NULL,
  41. [ShipName] [varchar](50) NULL,
  42. CONSTRAINT [PK_Orders] PRIMARY KEY CLUSTERED
  43. (
  44. [OrderID] ASC
  45. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  46. ) ON [PRIMARY]
  47. GO
  48. SET ANSI_PADDING OFF
  49. 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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. namespace MasterDetail.Controllers
  8. {
  9. [RoutePrefix("api/Company")]
  10. public class CompanyController : ApiController
  11. {
  12. //DbContext
  13. private CompanyDBEntities db = new CompanyDBEntities();
  14. public IQueryable<Customer> GetCustomers()
  15. {
  16. return db.Customers;
  17. }
  18. [Route("{customerId}")]
  19. public IQueryable<Order> GetOrdersByCustomer(string customerId)
  20. {
  21. return db.Orders.Where(o => o.CustomerID == customerId).AsQueryable();
  22. }
  23. }
  24. }

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

  1. var viewModel = function() {
  2. var self = this;
  3. self.CustomerID = ko.observable();
  4. self.CompanyName = ko.observable();
  5. self.ContactName = ko.observable();
  6. self.ContactTitle = ko.observable();
  7. self.City = ko.observable();
  8. self.Country = ko.observable();
  9. self.customerList = ko.observableArray([]);
  10. self.OrderID = ko.observable();
  11. self.EmployeeID = ko.observable();
  12. self.OrderDate = ko.observable();
  13. self.RequiredDate = ko.observable();
  14. self.ShippedDate = ko.observable();
  15. self.ShipName = ko.observable();
  16. self.OrdersList = ko.observableArray([]);
  17. var CompanyUri = '/api/Company/';
  18. function ajaxFunction(uri, method, data) {
  19. return $.ajax({
  20. type: method,
  21. url: uri,
  22. dataType: 'json',
  23. contentType: 'application/json',
  24. data: data ? JSON.stringify(data) : null
  25. }).fail(function (jqXHR, textStatus, errorThrown) {
  26. alert('Error: ' + errorThrown);
  27. });
  28. }
  29. //Customer List function which returns all customers from database.
  30. function customerList() {
  31. ajaxFunction(CompanyUri, 'GET').done(function (data) {
  32. self.customerList(data);
  33. });
  34. }
  35. //Detail Orders function accepts customer id as parameter and returns all orders related to customer id.
  36. self.detailOrders = function(customer) {
  37. ajaxFunction(CompanyUri + customer.CustomerID, 'GET').done(function (data) {
  38. self.OrdersList(data);
  39. });
  40. }
  41. customerList();
  42. };
  43. ko.applyBindings(new viewModel());

Now, from solution explorer panel, we are going to add MasterDetails.html file.


MasterDetails.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Master Detail :: Template</title>
  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. <!--CSS-->
  9. <link href="Content/bootstrap.min.css" rel="stylesheet" />
  10. </head>
  11. <body>
  12. <nav class="navbar navbar-default navbar-fixed-top">
  13. <div class="container-fluid">
  14. <div class="navbar-header">
  15. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
  16. <span class="sr-only">Toggle navigation</span>
  17. <span class="icon-bar"></span>
  18. <span class="icon-bar"></span>
  19. <span class="icon-bar"></span>
  20. </button>
  21. <a class="navbar-brand" href="#">Matser Detail - KnockOutJS</a>
  22. </div> <!-- END HEADER NAV -->
  23. </div> <!-- END CONTAINER -->
  24. </nav><!-- END NAV-->
  25. <div class="container" style="margin-top: 7%;">
  26. <div class="row">
  27. <div class="col-md-9">
  28. <!-- FORM -->
  29. <div class="panel panel-default">
  30. <div class="panel-heading"> <span class="glyphicon glyphicon glyphicon-tag" aria-hidden="true"></span> <b>Customer List </b></div>
  31. <div class="panel-body">
  32. <table class="table table-hover">
  33. <thead>
  34. <tr>
  35. <th><span class="glyphicon glyphicon glyphicon-eye-open" aria-hidden="true"></span></th>
  36. <th>Customer ID</th>
  37. <th>Company Name</th>
  38. <th>Contact Name</th>
  39. <th>Contact Title</th>
  40. <th>City</th>
  41. <th>Country</th>
  42. </tr>
  43. </thead> <!-- END THEAD -->
  44. <tbody data-bind="foreach: customerList">
  45. <tr>
  46. <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>
  47. <td> <span data-bind="text: CustomerID"></span> </td>
  48. <td> <span data-bind="text: CompanyName"></span> </td>
  49. <td> <span data-bind="text: ContactName"></span> </td>
  50. <td> <span data-bind="text: ContactTitle"></span> </td>
  51. <td> <span data-bind="text: City"></span> </td>
  52. <td> <span data-bind="text: Country"></span> </td>
  53. </tr>
  54. </tbody> <!-- END TBODY -->
  55. </table> <!-- END TABLE -->
  56. </div> <!-- END PANEL BODY-->
  57. </div><!-- END PANEL-->
  58. </div> <!-- END col-md-8 -->
  59. </div> <!-- END ROW-->
  60. <div class="row">
  61. <div class="col-md-10">
  62. <!-- FORM -->
  63. <div class="panel panel-default">
  64. <div class="panel-heading"> <span class="glyphicon glyphicon glyphicon-tag" aria-hidden="true"></span> <b>Orders by Customer </b></div>
  65. <div class="panel-body">
  66. <table class="table table-hover">
  67. <thead>
  68. <tr>
  69. <th>OrderID</th>
  70. <th>Customer ID</th>
  71. <th>Employee ID</th>
  72. <th>Order Date</th>
  73. <th>Required Date</th>
  74. <th>Shipped Date</th>
  75. <th>Ship Name</th>
  76. </tr>
  77. </thead> <!-- END THEAD -->
  78. <tbody data-bind="foreach: OrdersList">
  79. <tr>
  80. <td> <span data-bind="text: OrderID"></span> </td>
  81. <td> <span data-bind="text: CustomerID"></span> </td>
  82. <td> <span data-bind="text: EmployeeID"></span> </td>
  83. <td> <span data-bind="text: OrderDate"></span> </td>
  84. <td> <span data-bind="text: RequiredDate"></span> </td>
  85. <td> <span data-bind="text: ShippedDate"></span> </td>
  86. <td> <span data-bind="text: ShipName"></span></td>
  87. </tr>
  88. </tbody>
  89. </table>
  90. </div> <!-- END PANEL BODY-->
  91. </div><!-- END PANEL-->
  92. </div> <!-- END col-md-10 -->
  93. </div> <!-- END ROW-->
  94. </div> <!-- END CONTAINER-->
  95. <!-- JS -->
  96. <script src="Scripts/jquery-1.10.2.min.js"></script>
  97. <script src="Scripts/bootstrap.min.js"></script>
  98. <script src="Scripts/knockout-3.4.0.js"></script>
  99. <script src="Scripts/app.js"></script>
  100. </body>
  101. </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.