ASP.Net Web API Application Using Knockout.js

Introduction

 
This article explains how to create a simple application using knockout.js with the ASP.NET Web API. In this article we create a database, and we can update and delete the data of the database with this application. Knockout js is the JavaScript implementation for creating the rich, responsive display and editor user interfaces with a clean underlying data model. It is an open source library implemeted entirely in JavaScript.
 
Binding:
  • data-bind: It is used as HTML attributes.
  • Ko.oberserable: It is a property that wrap the object property with a custom function.
Use the following procedure to create a sample application.
 
Step 1
 
First we create a database with the table "CustomerInfo".
  1. use mudita  
  2. Create table CustomerInfo(CustNo int IDENTITY(1,1) PRIMARY KEY NOT NULL, CustName varchar(10) NOT NULL,Salary decimal(18,0)NOT NULL, DeptName varchar(50) Not Null)  
Step 2
 
Create a Web API application as in the following:
  • Start Visual Studio 2012.
  • From the Start window select "Installed" -> "Visual C#" -> "Web".
  • Select "ASP .NET MVC4 Web Application' and click on the "OK" button.
Select MVC4 Application
  • From the "MVC4 Project" window select "Web API".
Select Web API
  • Click on the "OK" button.
Step 3
 
Now add the ADO.NET Entity Data Model to the project.
  • In the Solution Explorer.
  • Right-click on the Model folder then select "Add" -> "New Item".
  • From the template window select "Installed" -> "Data" and then select "ADO.NET Data Model".
Add ADO.NET Model
 
Open a window select Generate from the database.
 
Generate Database
 
Click on the "Next" button and open a dialog box then click on "New Connection".
 
Create New Connection
 
Select the server name and database and click on the "Ok" button.
 
Select Table from database
 
Now from the entity data model wizard select the table and click on the "Finish" button.
 
ADO.NET Model
 
Step 4
 
Add an API Controller:
  • In the "Solution Explorer".
  • Right-click on the Controller folder and select "Add" -> "Controller".
  • Select an API controller with read /write actions using Entity Framework.
  • Select Model class and Data Context.
Add API Controller
  • Click on the "Add" button.
Step 5
 
Now we create an MVC Controller"CustomerInfoController.cs" and add a Create Action method "Create". And create a View of the "Create" action method.
 
Add View
 
Add the following code in the View:
  1. @{  
  2. ViewBag.Title = "Create";  
  3. }  
  4. <h2>Create</h2>  
  5. <html>  
  6.     <h2>Create</h2>  
  7.   
  8.     <head>  
  9.         <script src="~/Scripts/jquery-1.8.2.js"></script>  
  10.         <script src="~/Scripts/knockout-2.2.0.js"></script>  
  11.         <script src="~/Scripts/knockout.mapping-latest.js"></script>  
  12.         <link href="~/Content/Site.css" rel="stylesheet" />  
  13.     </head>  
  14.   
  15.     <body>  
  16.         <form>  
  17.             <table>  
  18.                 <tr>  
  19.                     <td>  
  20.                         <!--Bind the TextBoxes in the Table to the observable properties defined into the ViewModel -->  
  21.                         <table id="tbldml">  
  22.                             <tr>  
  23.                                 <td>CustNo</td>  
  24.                                 <td>  
  25.                                     <input type="text" id="txteno" data-bind="value: $root.CustNo" disabled="disabled" /></td>  
  26.                             </tr>  
  27.                             <tr>  
  28.                                 <td>CustName</td>  
  29.                                 <td>  
  30.                                     <input type="text" id="txtename" data-bind="value: $root.CustName" /></td>  
  31.                             </tr>  
  32.                             <tr>  
  33.                                 <td>Salary</td>  
  34.                                 <td>  
  35.                                     <input type="text" id="txtsal" data-bind="value: $root.Salary" /></td>  
  36.                             </tr>  
  37.                             <tr>  
  38.                                 <td>DeptName</td>  
  39.                                 <td>  
  40.                                     <input type="text" id="txtdname" data-bind="value: $root.DeptName" /></td>  
  41.                             </tr>  
  42.                             <tr>  
  43.                                 <!--The click binding has the JavaScirpt methods passed to it-->  
  44.                                 <td>  
  45.                                     <button data-bind="click :$root.save">Save</button></td>  
  46.                                 <td>  
  47.                                     <button data-bind="click: $root.update">Update</button></td>  
  48.                             </tr>  
  49.                         </table>  
  50.                     </td>  
  51.                     <td>  
  52.                         <div class="FixedContainer">  
  53.                             <table data-bind="visible:  Customers().length>0" style="border: double">  
  54.                                 <thead>  
  55.                                     <tr>  
  56.                                         <td>CustNo</td>  
  57.                                         <td>CustName</td>  
  58.                                         <td>Salary</td>  
  59.                                         <td>DeptName</td>  
  60.                                         <td></td>  
  61.                                     </tr>  
  62.                                 </thead>  
  63.                                 <!--Iterate through an observableArray using foreach-->  
  64.                                 <tbody data-bind="foreach: Customers">  
  65.                                     <tr style="border: solid" data-bind="click: $root.getselectedcustomer" id="updtr">  
  66.                                         <td><span data-bind="text:  CustNo"></span></td>  
  67.                                         <td><span data-bind="text:  CustName"></span></td>  
  68.                                         <td><span data-bind="text: Salary"></span></td>  
  69.                                         <td><span data-bind="text: DeptName"></span></td>  
  70.                                         <td>  
  71.                                             <button data-bind="click: $root.deleterec">Delete</button></td>  
  72.                                     </tr>  
  73.                                 </tbody>  
  74.                             </table>  
  75.                         </div>  
  76.                     </td>  
  77.                 </tr>  
  78.             </table>  
  79.         </form>  
  80.         <script type="text/javascript">  
  81.         var CustViewModel = function() {  
  82.             //Make the self as 'this' reference  
  83.             var self = this;  
  84.             //Declare observable which will be bind with UI  
  85.             self.CustNo = ko.observable("0");  
  86.             self.CustName = ko.observable("");  
  87.             self.Salary = ko.observable("");  
  88.             self.DeptName = ko.observable("");  
  89.             //The Object which stored data entered in the observables  
  90.             var CustData = {  
  91.                 CustNo: self.CustNo,  
  92.                 CustName: self.CustName,  
  93.                 Salary: self.Salary,  
  94.                 DeptName: self.DeptName,  
  95.             };  
  96.             //Declare an ObservableArray for Storing the JSON Response  
  97.             self.Customers = ko.observableArray([]);  
  98.             GetCustomers(); //Call the Function which gets all records using ajax call  
  99.             self.save = function() {  
  100.                 //Ajax call to Insert the Customer record  
  101.                 $.ajax({  
  102.                     type: "POST",  
  103.                     url: "http://localhost:55333//api/CustomerInfoAPI",  
  104.                     data: ko.toJSON(CustData), //Convert the Observable Data into JSON  
  105.                     contentType: "application/json",  
  106.                     success: function(data) {  
  107.                         alert("Record Added Successfully");  
  108.                         self.CustNo(data.CustNo);  
  109.                         alert("The New Customer Id :" + self.CustNo());  
  110.                         GetCustomers();  
  111.                     },  
  112.                     error: function() {  
  113.                         alert("Failed");  
  114.                     }  
  115.                 });  
  116.                 //Ends Here  
  117.             };  
  118.             self.update = function() {  
  119.                 var url = "http://localhost:55333//api/CustomerInfoAPI/" + self.CustNo();  
  120.                 alert(url);  
  121.                 $.ajax({  
  122.                     type: "PUT",  
  123.                     url: url,  
  124.                     data: ko.toJSON(CustData),  
  125.                     contentType: "application/json",  
  126.                     success: function(data) {  
  127.                         alert("Record Updated Successfully");  
  128.                         GetCustomers();  
  129.                     },  
  130.                     error: function(error) {  
  131.                         alert(error.status + "<!----!>" + error.statusText);  
  132.                     }  
  133.                 });  
  134.             };  
  135.             //Function to perform DELETE Operation  
  136.             self.deleterec = function(customer) {  
  137.                 $.ajax({  
  138.                     type: "DELETE",  
  139.                     url: "http://localhost:55333//api/CustomerInfoAPI/" + customer.CustNo,  
  140.                     success: function(data) {  
  141.                         alert("Record Deleted Successfully");  
  142.                         GetCustomers(); //Refresh the Table  
  143.                     },  
  144.                     error: function(error) {  
  145.                         alert(error.status + "<--and--> " + error.statusText);  
  146.                     }  
  147.                 });  
  148.             };  
  149.   
  150.             function GetCustomers() {  
  151.                 $.ajax({  
  152.                     type: "GET",  
  153.                     url: "http://localhost:55333//api/CustomerInfoAPI",  
  154.                     contentType: "application/json; charset=utf-8",  
  155.                     dataType: "json",  
  156.                     success: function(data) {  
  157.                         self.Customers(data); //Put the response in ObservableArray  
  158.                     },  
  159.                     error: function(error) {  
  160.                         alert(error.status + "<--and--> " + error.statusText);  
  161.                     }  
  162.                 });  
  163.                 //Ends Here  
  164.             }  
  165.             //Function to Display record to be updated  
  166.             self.getselectedcustomer = function(customer) {  
  167.                 self.CustNo(customer.CustNo),  
  168.                     self.CustName(customer.CustName),  
  169.                     self.Salary(customer.Salary),  
  170.                     self.DeptName(customer.DeptName)  
  171.             };  
  172.         };  
  173.         ko.applyBindings(new CustViewModel());  
  174.         </script>  
  175.     </body>  
  176.   
  177. </html>  
Step 6
 
Execute the application. Fill in a record and click on the "Save" button. It then displays a successful submission message.
 
Save Data
 
Display Save successful message
 
Update the record. Change a record and click on the "Update" button. Here we update "Tanya" with "Priya". It updates the record.
Update Record
For deleting the record click on the "Delete" button. You can see that it deletes the record.
Update Record
Record deleted
See Data Deleted
 
We can also see our database using the command:
  1. Select * from CustomerInfo  


Similar Articles