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:
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:
Select MVC4 Application
Select Web API
Step 3
Now add the ADO.NET Entity Data Model to the project.
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:
Add API Controller
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. <head>
  8. <script src="~/Scripts/jquery-1.8.2.js"></script>
  9. <script src="~/Scripts/knockout-2.2.0.js"></script>
  10. <script src="~/Scripts/knockout.mapping-latest.js"></script>
  11. <link href="~/Content/Site.css" rel="stylesheet" />
  12. </head>
  13. <body>
  14. <form>
  15. <table>
  16. <tr>
  17. <td>
  18. <!--Bind the TextBoxes in the Table to the observable properties defined into the ViewModel -->
  19. <table id="tbldml">
  20. <tr>
  21. <td>CustNo</td>
  22. <td>
  23. <input type="text" id="txteno" data-bind="value: $root.CustNo" disabled="disabled" /></td>
  24. </tr>
  25. <tr>
  26. <td>CustName</td>
  27. <td>
  28. <input type="text" id="txtename" data-bind="value: $root.CustName" /></td>
  29. </tr>
  30. <tr>
  31. <td>Salary</td>
  32. <td>
  33. <input type="text" id="txtsal" data-bind="value: $root.Salary" /></td>
  34. </tr>
  35. <tr>
  36. <td>DeptName</td>
  37. <td>
  38. <input type="text" id="txtdname" data-bind="value: $root.DeptName" /></td>
  39. </tr>
  40. <tr>
  41. <!--The click binding has the JavaScirpt methods passed to it-->
  42. <td>
  43. <button data-bind="click :$root.save">Save</button></td>
  44. <td>
  45. <button data-bind="click: $root.update">Update</button></td>
  46. </tr>
  47. </table>
  48. </td>
  49. <td>
  50. <div class="FixedContainer">
  51. <table data-bind="visible: Customers().length>0" style="border: double">
  52. <thead>
  53. <tr>
  54. <td>CustNo</td>
  55. <td>CustName</td>
  56. <td>Salary</td>
  57. <td>DeptName</td>
  58. <td></td>
  59. </tr>
  60. </thead>
  61. <!--Iterate through an observableArray using foreach-->
  62. <tbody data-bind="foreach: Customers">
  63. <tr style="border: solid" data-bind="click: $root.getselectedcustomer" id="updtr">
  64. <td><span data-bind="text: CustNo"></span></td>
  65. <td><span data-bind="text: CustName"></span></td>
  66. <td><span data-bind="text: Salary"></span></td>
  67. <td><span data-bind="text: DeptName"></span></td>
  68. <td>
  69. <button data-bind="click: $root.deleterec">Delete</button></td>
  70. </tr>
  71. </tbody>
  72. </table>
  73. </div>
  74. </td>
  75. </tr>
  76. </table>
  77. </form>
  78. <script type="text/javascript">
  79. var CustViewModel = function() {
  80. //Make the self as 'this' reference
  81. var self = this;
  82. //Declare observable which will be bind with UI
  83. self.CustNo = ko.observable("0");
  84. self.CustName = ko.observable("");
  85. self.Salary = ko.observable("");
  86. self.DeptName = ko.observable("");
  87. //The Object which stored data entered in the observables
  88. var CustData = {
  89. CustNo: self.CustNo,
  90. CustName: self.CustName,
  91. Salary: self.Salary,
  92. DeptName: self.DeptName,
  93. };
  94. //Declare an ObservableArray for Storing the JSON Response
  95. self.Customers = ko.observableArray([]);
  96. GetCustomers(); //Call the Function which gets all records using ajax call
  97. self.save = function() {
  98. //Ajax call to Insert the Customer record
  99. $.ajax({
  100. type: "POST",
  101. url: "http://localhost:55333//api/CustomerInfoAPI",
  102. data: ko.toJSON(CustData), //Convert the Observable Data into JSON
  103. contentType: "application/json",
  104. success: function(data) {
  105. alert("Record Added Successfully");
  106. self.CustNo(data.CustNo);
  107. alert("The New Customer Id :" + self.CustNo());
  108. GetCustomers();
  109. },
  110. error: function() {
  111. alert("Failed");
  112. }
  113. });
  114. //Ends Here
  115. };
  116. self.update = function() {
  117. var url = "http://localhost:55333//api/CustomerInfoAPI/" + self.CustNo();
  118. alert(url);
  119. $.ajax({
  120. type: "PUT",
  121. url: url,
  122. data: ko.toJSON(CustData),
  123. contentType: "application/json",
  124. success: function(data) {
  125. alert("Record Updated Successfully");
  126. GetCustomers();
  127. },
  128. error: function(error) {
  129. alert(error.status + "<!----!>" + error.statusText);
  130. }
  131. });
  132. };
  133. //Function to perform DELETE Operation
  134. self.deleterec = function(customer) {
  135. $.ajax({
  136. type: "DELETE",
  137. url: "http://localhost:55333//api/CustomerInfoAPI/" + customer.CustNo,
  138. success: function(data) {
  139. alert("Record Deleted Successfully");
  140. GetCustomers(); //Refresh the Table
  141. },
  142. error: function(error) {
  143. alert(error.status + "<--and--> " + error.statusText);
  144. }
  145. });
  146. };
  147. function GetCustomers() {
  148. $.ajax({
  149. type: "GET",
  150. url: "http://localhost:55333//api/CustomerInfoAPI",
  151. contentType: "application/json; charset=utf-8",
  152. dataType: "json",
  153. success: function(data) {
  154. self.Customers(data); //Put the response in ObservableArray
  155. },
  156. error: function(error) {
  157. alert(error.status + "<--and--> " + error.statusText);
  158. }
  159. });
  160. //Ends Here
  161. }
  162. //Function to Display record to be updated
  163. self.getselectedcustomer = function(customer) {
  164. self.CustNo(customer.CustNo),
  165. self.CustName(customer.CustName),
  166. self.Salary(customer.Salary),
  167. self.DeptName(customer.DeptName)
  168. };
  169. };
  170. ko.applyBindings(new CustViewModel());
  171. </script>
  172. </body>
  173. </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