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
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
- {
-
- 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);
-
- });
- }
-
-
- function customerList() {
-
- ajaxFunction(CompanyUri, 'GET').done(function (data) {
-
- self.customerList(data);
-
- });
-
- }
-
-
- 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
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.