Introduction to Knockout.js and CRUD Operations in ASP.Net Web Forms Using Knockout.JS


The development paradigm has been changing rapidly for the last few years. The out-of-box technologies have been introduced to develop the applications as fast, scalable, with an extensible structure, easy to maintain, and easy to use. "knockout.js" is an example of such emerging technologies. This is my opportunity to explain the concept and topic my way.
We'll be explaining the technology from a basic to an advanced level by just following a road-map.
Our Road-map
We'll learn "knockout.js" in the following three parts:
Part 1: Introduction to "knockout.js" and CRUD Operations in ASP.Net Web Forms using "knockout.js"
We'll explain this part beginning with an introduction to Knockout, MVVM, and the Observer Pattern. Then by setting up a basic environment in knockout.js, create an ASP.Net web forms application that does CRUD operations.
In today's quickly changing trends, the development of data-driven apps depends largely on JavaScript and JavaScript based libraries such as jQuery. Client-side programming appears to become complex and it is complex because the user interface becomes richer and richer. In scenarios like this the data binding and dependency tracking are highly desirable in the applications for further extensibility of the application. Knockout JS fulfills these rich requirements on the client-side programming and makes a developer's life easy and joyful. Let's explain KO in detail.
The "knockout.js" (KO) file is basically a JavaScript library that enables Declarative Bindings using an "Observable" ViewModel on the client (browser) using an Observer Pattern approach, enabling the UI to bind and refresh itself automatically whenever the bound data is modified. The "knockout.js" file provides its own templating pattern that helps us to bind our view model data easily. KO works on the MVVM pattern, in other words Model-View-ViewModel.
As the architecture is shown, Views interact with View Models in a two-way binding manner, in other words when the model is changed the view updates itself and when the view is updated, the model also updates itself instantaneously.
KO provides the following 3 most important features:
  • Automatic Refresh of UI
  • Two-way binding
  • Templating
The entire idea of KO derives from these three major functionalities. KO also helps in developing single-page applications (SPAs). SPAs are an out-of-the-box new way of developing Rich Internet Applications (RIAs) in today's era.
Model-View-View Model (MVVM)
When we develop a rich UI internet-based application, we create views (UI like HTML and aspx pages) using server controls, HTML controls and then extend our application by writing business logic behind those views like event handling, property binding, and creation of entities. This approach increases complexities when an application is too large. Here we require the separation of concerns and maintainability of the application, especially on the client-side.
The MVVM pattern includes the following three key parts:
  1. Model (business rules, data access, model classes, the data displayed in a UI)
  2. View (User Interface (such as HTML, aspx, cshtml and so on))
  3. ViewModel (event handling, binding, and business logic) 
Model refers to our application data and domain model, in other words entities. In a traditional ASP.NET web application, the data is basically stored inside a database or files and the UI fetches the data using a client-server request like Ajax or directly bound to itself.
View Model contains the User Interface level operations/methods/functions, performed on model data to bind the outcome to the view. The operations include business logic validations and checks to be performed before binding data to the UI. View models act as an interface between model and views and act as a wrapper over the model prior to binding to the Views.
View is the user interface of our application. View talks to the View Model to invoke certain methods/operations as explained above. View gets updated automatically whenever data from the View Model changes.
MVVM provides a clear separation of concerns between the User Interface (UI) and the business logic.
In the MVC pattern, a view acts as the broker agent between the Model (the data displayed in the View) and the Controller (server-side endpoint that takes data from the View and performs some action on that data and provides a response).
Observables for two way binding
KO provides Observables in the library to be bound to UI elements and simultaneously code is written to view models, so that when the view updates the data the model updates itself and vice versa. For example, in the following code:
  1. <tr>  
  2.     <td>Batch :</td>  
  3.     <td><input data-bind="value: Batch" /></td>  
  4.     <td><span data-bind="text: Batch" /></td>  
  5. </tr>  
  6. <tr>  
  7.     <td>Address :</td>  
  8.     <td><input data-bind="value: Address" /></td>  
  9.     <td><span data-bind="text: Address" /></td>  
  10. </tr>  
  11. <tr>  
  12.     <td>Class :</td>  
  13.     <td><input data-bind="value: Class" /></td>  
  14.     <td><span data-bind="text: Class" /></td>  
  15. </tr>  
The code above shows a part of a view, you can see the elements are bound to properties like text and value, these properties are provided by KO, and the right side of these properties are property key names that are bound in view-models using observables as shown below.
  1. var self = this;  
  2. self.Batch = ko.observable();  
  3. self.Address = ko.observable();  
  4. self.Class = ko.observable(); 
So this would be the code in the View model; we'll be explaining all this in detail.
Note: data-bind is an HTML5 attribute.
Setting up Environment in Visual Studio for KO
We go step-by-step to set up a Knockout JavaScript environment in Visual Studio.
The prerequisite is that Visual Studio must be a version equal to or 12. I am using Visual Studio 2013 Express.
Step 1:
Open Visual Studio and create a simple ASP.Net application, I have given it the name KOSetup.
Creating Application
Step 2:  Right-click on the project, and in the context menu select "Manage Nuget packages" to install jQuery and KO.
Nuget packages
Step 3:  Type "jQuery" in the search text box to get the latest compatible jQuery library. Click "install" to install the library.
jQuery library
Step 4:  In a similar fashion, search 'knockout' in the search TextBox and install the knockoutjs library into your application.
knockoutjs library
Step 5: Our solution will look as in the following. We have a folder created named "Scripts" and that contains jQuery and Knockout libraries.
contains jQuery and knockout libraries
Step 6:  Now right-click the project and add an aspx page. I named that page "LearnKO.aspx".
aspx page
Step 7: Similarly create a JavaScript file and add that to the project. I named that file "LearnKO.js".
javascript file
Step 8: Open the "learnKO.js" file and drag the jQuery file and "knockout.js" library file to the "LearKO.js" file, we see in the following picture that references for both files are created on the JavaScript file. We did this because to provide IntelliSense support for jQuery and Knockout on our "LearnKO.js" file.
jQuery file and knockout.js library file
Step 9: Write the document.ready function of jQuery in our LearnKO.js file. The document.ready function is fired when our HTML document object model has been loaded into the browser.
document ready fuction
This is all we need to do to set up Knockout. Now we know how to set up the initial environment to use "knockout.js" in our application.
setup knockout
We proceed now to create the application, talk to a database, and create a template and view model.
Creating a Knockout application
Step 10:
For communication with a database, add the Entity Framework library in the same manner as we added jQuery and KO. Installing the Entity Framework library will add the Entity Framework DLL to the project. We'll talk to the database using the Entity Framework of Microsoft. Alternatively there are many ways to interface with a database, like ADO.Net, LINQ to SQL, and so on. But first things first, create a database; you need it to use SQL Server. I've provided a script for that.
create a data base
Step 11: Right-click the project and add an ADO.NET Entity Data Model, click "Add" and use the following procedure:
ADO.NET Entity data Model
Step 12: The following is the second step of the Entity Data Model, you can choose model contents from the database you already created. So select "Generate From database". Click Next.
Entity Data Model
Step 13: Choose the table you want to add, in other words the Student table, as shown below in the figure. Name the model "LearningKOModel". Click "Finish".
Student table
Step 14: We get certain files in our solution, like context and tt files. We also get a "Student.CS" file, that will act as our server-side domain model. The context class contains the data communication methods of the Entity Framework.
context class
Step 15:
Write three methods using the Entity Framework in our "aspx.cs" page. One method fetches all the students and another method saves and deletes students to/from the database, as shown below. Mark them as web methods so that they could be called from the client-side.
web method
  1. #region Public Web Methods.  
  2. /// <summary>  
  3. /// Gets Student Details  
  4. /// </summary>  
  5. /// <returns></returns>  
  6. [WebMethod]  
  7. public static Student[] FetchStudents() {  
  8.   LearningKOEntities dbEntities = new LearningKOEntities();  
  9.   var data = (from item in dbEntities.Students orderby item.StudentId select item).Take(5);  
  10.   return data.ToArray();  
  11. }  
  13. /// <summary>  
  14. /// Saves Student Details  
  15. /// </summary>  
  16. /// <param name="data"></param>  
  17. /// <returns></returns>  
  18. [WebMethod]  
  19. public static string SaveStudent(Student[] data) {  
  20.   try {  
  21.       var dbContext = new LearningKOEntities();  
  22.       var studentList = from dbStududent in dbContext.Students select dbStududent;  
  23.       foreach(Student userDetails in data) {  
  24.           var student = new Student();  
  25.           if (userDetails != null) {  
  26.               student.StudentId = userDetails.StudentId;  
  27.               student.FirstName = userDetails.FirstName;  
  28.               student.LastName = userDetails.LastName;  
  29.               student.Address = userDetails.Address;  
  30.               student.Age = userDetails.Age;  
  31.               student.Gender = userDetails.Gender;  
  32.               student.Batch = userDetails.Batch;  
  33.               student.Class = userDetails.Class;  
  34.               student.School = userDetails.School;  
  35.               student.Domicile = userDetails.Domicile;  
  36.           }  
  37.           Student stud = (from st in studentList where st.StudentId == student.StudentId select st).FirstOrDefault();  
  38.           if (stud == null)  
  39.               dbContext.Students.Add(student);  
  40.           dbContext.SaveChanges();  
  41.       }  
  42.       return "Data saved to database!";  
  43.   } catch (Exception ex) {  
  44.       return "Error: " + ex.Message;  
  45.   }  
  46. }  
  48. /// <summary>  
  49. /// Deletes Student Details  
  50. /// </summary>  
  51. /// <param name="data"></param>  
  52. /// <returns></returns>  
  53. [WebMethod]  
  54. public static string DeleteStudent(Student data) {  
  55.   try {  
  56.       var dbContext = new LearningKOEntities();  
  57.       var student = dbContext.Students.FirstOrDefault(userId => userId.StudentId == data.StudentId);  
  58.       if (student != null) {  
  59.           if (student != null) {  
  60.               dbContext.Students.Remove(student);  
  61.               dbContext.SaveChanges();  
  62.           }  
  63.       }  
  64.       return "Data deleted from database!";  
  66.   } catch (Exception ex) {  
  67.       return "Error: " + ex.Message;  
  68.   }  
  69. }  
  70. #endregion  
Step 16: Open the aspx page we created and add the following code to it, the code provides templates in HTML bound to model properties, one to add a Student and the other to display a Student List.
  1. <table style="width: 100%;">  
  2.     <tbody>  
  3.         <tr>  
  4.             <th style="width: 100px;">Property Name</th>  
  5.             <th style="width: 100px;">Enter Value</th>  
  6.             <th style="width: 100px;">  
  7.                 Example of two Way Binding  
  8.             </th>  
  9.         </tr>  
  10.     </tbody>  
  11.     <tr>  
  12.         <td>Student ID (int):</td>  
  13.         <td><input data-bind="value: StudentId" /></td>  
  14.         <!--,valueUpdate:'keypress'-->  
  15.         <td><span data-bind="text: StudentId" /></td>  
  16.     </tr>  
  17.     <tr>  
  18.         <td>First Name :</td>  
  19.         <td><input data-bind="value: FirstName" /></td>  
  20.         <td><span data-bind="text: FirstName" /></td>  
  21.     </tr>  
  22.     <tr>  
  23.         <td>Last Name :</td>  
  24.         <td><input data-bind="value: LastName" /></td>  
  25.         <td><span data-bind="text: LastName" /></td>  
  26.     </tr>  
  27.     <tr>  
  28.         <td>Student Age (int) :</td>  
  29.         <td><input data-bind="value: Age" /></td>  
  30.         <td><span data-bind="text: Age" /></td>  
  31.     </tr>  
  32.     <tr>  
  33.         <td>Gender :</td>  
  34.         <td><select data-bind="options: Genders, value: Gender, optionsCaption: 'Select Gender...'"></select></td>  
  35.         <td><span data-bind="text: Gender" /></td>  
  36.     </tr>  
  37.     <tr>  
  38.         <td>Batch :</td>  
  39.         <td><input data-bind="value: Batch" /></td>  
  40.         <td><span data-bind="text: Batch" /></td>  
  41.     </tr>  
  42.     <tr>  
  43.         <td>Address :</td>  
  44.         <td><input data-bind="value: Address" /></td>  
  45.         <td><span data-bind="text: Address" /></td>  
  46.     </tr>  
  47.     <tr>  
  48.         <td>Class :</td>  
  49.         <td><input data-bind="value: Class" /></td>  
  50.         <td><span data-bind="text: Class" /></td>  
  51.     </tr>  
  52.     <tr>  
  53.         <td>School :</td>  
  54.         <td><input data-bind="value: School" /></td>  
  55.         <td><span data-bind="text: School" /></td>  
  56.     </tr>  
  57.     <tr>  
  58.         <td>Domicile :</td>  
  59.         <td>  
  60.             <select data-bind="options: Domiciles, value: Domicile, optionsCaption: 'Select Domicile...'"></select></td>  
  61.         <td><span data-bind="text: Domicile" /></td>  
  62.     </tr>  
  63.     <tr>  
  64.         <td colspan="3"><button type="button" data-bind="click: AddStudent">Add Student</button>  
  65.             <button type="button" data-bind="click: SaveStudent">Save Student To Database</button>  
  66.         </td>  
  67.     </tr>  
  68. </table>  
  69. </div>  
  70. <div style="width: 70%; float: left; display: inline-block;">  
  71.     <h2>List of Students</h2>  
  72.     <table style="width: 100%;" data-bind="visible: Students().length > 0" border="0">  
  73.         <tr>  
  74.             <th>Student Id</th>  
  75.             <th>First Name</th>  
  76.             <th>Last Name</th>  
  77.             <th>Age</th>  
  78.             <th>Gender</th>  
  79.             <th>Batch</th>  
  80.             <th>Address</th>  
  81.             <th>Class</th>  
  82.             <th>School</th>  
  83.             <th>Domicile</th>  
  84.         </tr>  
  85.         <tbody data-bind="foreach: Students">  
  86.             <tr>  
  87.                 <td><span data-bind="text: StudentId" /></td>  
  88.                 <td><input data-bind="value: FirstName" /></td>  
  89.                 <td><input data-bind="value: LastName" /></td>  
  90.                 <td><input data-bind="value: Age" /></td>  
  91.                 <td><select data-bind="options: $root.Genders, value: Gender"></select></td>  
  92.                 <td><input data-bind="value: Batch" /></td>  
  93.                 <td><input data-bind="value: Address" /></td>  
  94.                 <td><input data-bind="value: Class" /></td>  
  95.                 <td><input data-bind="value: School" /></td>  
  96.                 <td><select data-bind="options: $root.Domiciles, value: Domicile"></select></td>  
  97.                 <td><a href="#" data-bind="click: $root.DeleteStudent">Delete</a></td>  
  98.             </tr>  
  99.         </tbody>  
  100.     </table>  
There are two HTML tables, one for adding a student to the database and the other showing all the students having a delete anchor link to delete the student, these template properties will be bound in the view model, where we write a method to communicate with the database and call the Web Methods we created in the "aspx.cs" page. The Viewmodel also contains observables to be bound to these properties.
Step 17: Now it's time to create the ViewModel. Open the "learnKO.js" file and add code to fetch, save and delete students and observables bound to properties bound on controls of the HTML page.
  1. /// <reference path="jquery-2.0.3.min.js" />  
  2. /// <reference path="knockout-3.0.0.js" />  
  3. function Student(data) {  
  4.     this.StudentId = ko.observable(data.StudentId);  
  5.     this.FirstName = ko.observable(data.FirstName);  
  6.     this.LastName = ko.observable(data.LastName);  
  7.     this.Age = ko.observable(data.Age);  
  8.     this.Gender = ko.observable(data.Gender);  
  9.     this.Batch = ko.observable(data.Batch);  
  10.     this.Address = ko.observable(data.Address);  
  11.     this.Class = ko.observable(data.Class);  
  12.     this.School = ko.observable(data.School);  
  13.     this.Domicile = ko.observable(data.Domicile);  
  14. }  
  16. function StudentViewModel() {  
  17.     var self = this;  
  18.     self.Domiciles = ko.observableArray(['Delhi''Outside Delhi']);  
  19.     self.Genders = ko.observableArray(['Male''Female']);  
  20.     self.Students = ko.observableArray([]);  
  21.     self.StudentId = ko.observable();  
  22.     self.FirstName = ko.observable();  
  23.     self.LastName = ko.observable();  
  24.     self.Age = ko.observable();  
  25.     self.Batch = ko.observable();  
  26.     elf.Address = ko.observable();  
  27.     self.Class = ko.observable();  
  28.     self.School = ko.observable();  
  29.     self.Domicile = ko.observable();  
  30.     self.Gender = ko.observable();  
  31.     self.AddStudent = function() {  
  32.         self.Students.push(new Student({  
  33.             StudentId: self.StudentId(),  
  34.             FirstName: self.FirstName(),  
  35.             LastName: self.LastName(),  
  36.             Domicile: self.Domicile(),  
  37.             Age: self.Age(),  
  38.             Batch: self.Batch(),  
  39.             Address: self.Address(),  
  40.             Class: self.Class(),  
  41.             School: self.School(),  
  42.             Gender: self.Gender()  
  43.         }));  
  44.         self.StudentId(""), self.FirstName(""), self.LastName(""), self.Domicile(""), self.Age(""), self.Batch(""), self.Address(""), self.Class(""), self.School(""), self.Gender("")  
  45.     };  
  46.     self.DeleteStudent = function(student) {  
  47.         $.ajax({  
  48.             type: "POST",  
  49.             url: 'LearnKO.aspx/DeleteStudent',  
  50.             data: ko.toJSON({ data: student }),  
  51.             contentType: "application/json; charset=utf-8",  
  52.             success: function(result) {  
  53.                 alert(result.d);  
  54.                 self.Students.remove(student)  
  55.             },  
  56.             error: function(err) {  
  57.                 alert(err.status + " - " + err.statusText);  
  58.             }  
  59.         });  
  60.     };  
  61.     self.SaveStudent = function() {  
  62.         $.ajax({  
  63.             type: "POST",  
  64.             url: 'LearnKO.aspx/SaveStudent',  
  65.             data: ko.toJSON({ data: self.Students }),  
  66.             contentType: "application/json; charset=utf-8",  
  67.             success: function(result) {  
  68.                 alert(result.d);  
  69.             },  
  70.             error: function(err) {  
  71.                 alert(err.status + " - " + err.statusText);  
  72.             }  
  73.         });  
  74.     };  
  75.     $.ajax({  
  76.         type: "POST",  
  77.         url: 'LearnKO.aspx/FetchStudents',  
  78.         contentType: "application/json; charset=utf-8",  
  79.         dataType: "json",  
  80.         success: function(results) {  
  81.             var students = $.map(results.d, function(item) {  
  82.                 return new Student(item)  
  83.             });  
  84.             self.Students(students);  
  85.         },  
  86.         error: function(err) {  
  87.             alert(err.status + " - " + err.statusText);  
  88.         }  
  89.     })  
  90. }  
  91. $(document).ready(function() {  
  92.     ko.applyBindings(new StudentViewModel());  
  93. });  
We create StudentViewModel() as our primary view model JavaScript function, which contains all the business logic and operations.
We bind this View model on the document ready function by the KO method named "applyBindings".This initializes our view model, ko.applyBindings(new StudentViewModel());
The function Student(data) contains observables bound to model properties.
We can create observable arrays of Domiciles and genders to bind to the dropdown list of our HTML. Ko provides these observables and other such properties to bind to the model.
. observable: Used to define model/entity properties. If these properties are bound with the user interface and when the value for these properties are updated, the UI elements are automatically bound with these properties and will be updated with the new value instantaneously.
For example, in the following, StudentId is the observable property; KO represents an object for the "knockout.js" library.
  1. this.StudentId = ko.observable("1"); 
The value of the observable is read as:
  1. var id= this. StudentId (); 
. observableArray: observableArray represents a collection of data elements that require notifications. It's used to bind with the List kind of elements.
For example:
  1. this.Students = ko.observableArray([]);  
. applyBindings: This is used to activate Knockout for the current HTML document or a specific UI element in an HTML document. The parameter for this method is the view-model that is defined in JavaScript. This ViewModel contains the observable, observableArray, and various methods.
Various other types of binding are used in this article:
o click: Represents a click event handler added to the UI element so that the JavaScript function is called.
o value: This represents the value binding with the UI element's value property to the property defined into the ViewModel.
The value binding should be used with <input> , <select> , <textarea>.
o visible: This is used to hide or unhide the UI element based upon the value ed to its binding.
o Text: This represents the text value of the parameter ed to the UI element.
Step 18: Include JavaScript files and stylesheet (you can create your own stylesheet file) to the head section of the aspx page.
js files and stylesheet
Step 19: Press F5 to run the application, and we'll be shown a page having HTML controls as follows.
run the application
The list of students shows the list of students from the database, bound to the viewmodel's event.
Try to create a new student and add a student then save it to the database, it will automatically be added to the right-hand side list.
We can see that the Domicile and Genders drop-down lists are bound to our Viewmodel's properties.
Note: Do not give a string in the StudentId and Age since no validation is put on those fields, the code may break.
Create Student
enter Student Detail
Student added to list and database
Student added to list and database
Job Done!
Now you can say that you have become a "knockout.js" developer.


We learned a lot in this article about how to set up "knockout.js" in Visual Studio, many theories, and also created a sample application just to get hands-on experience with the concept. There are numerous articles and blogs related to this concept. You can explore more and more to learn. In the next article, I'll explain the creation of a sample application and performing CRUD operations in MVC4 with Knockout JavaScript and Entity Framework, now pat your back for having done a great job by learning a new concept.
learning a new concept
Note: a few of the images in this article were obtained via Google search. You can follow my articles at

Similar Articles