Download Source Code
I) Introduction
II) Our Road-map
- Part 1: Introduction to Knockout.js and CRUD Operations in ASP.NET Web Forms using Knockout.JS and Entity Framework.
- Part 2: Complete end to end CRUD operations using Knockout.JS and Entity Framework in MVC4 application.
III) Part 1: Introduction to Knockout.js and CRUD Operations in ASP.NET Web Forms using Knockout.JS
IV) Knockout
ViewModel
on the client (browser) following observer pattern approach, enabling UI to bind and refresh itself automatically whenever the data bound is modified. Knockout.JS provides its own templating pattern that helps us to bind our view model data easily. KO works on MVVM pattern i.e. Model-View-ViewModel.- Automatic Refresh of UI
- Two way binding
- Templating
V) Model-View-View Model (MVVM)
Model
(Business rule, data access, model classes, Data displayed in UI)View
(User interface (html, aspx, cshtml…))ViewModel
(Event handling, binding, business logic)
VI) Observables for Two Way Binding
<tr> <td>Batch :</td> <td> <input data-bind="value: Batch" /></td> <td><span data-bind="text: Batch" /></td> </tr> <tr> <td>Address :</td> <td> <input data-bind="value: Address" /></td> <td><span data-bind="text: Address" /></td> </tr> <tr> <td>Class :</td> <td> <input data-bind="value: Class" /></td> <td><span data-bind="text: Class" /></td> </tr>
text
and value
, these properties are provided by KO, and the right side of these properties are property key names which are bind in view-models with the help of observables like shown below:var self = this; self.Batch = ko.observable(); self.Address = ko.observable(); self.Class = ko.observable();
VII) Setting up Environment in Visual Studio for KO








document.ready
function of jquery in our LearnKO.js file. Document.ready
function is fired when our HTML document object model is loaded in browser.

VIII) Creating Knockout Application




Student
table as shown below in the figure. Name the model asLearningKOModel
. Click Finish.

Students
and another method to save and delete a student to/from database, as shown below. Mark them as web method so that they could be called from client side.
#region Public Web Methods. /// <summary> /// Gets Student Details /// </summary> /// <returns></returns> [WebMethod] public static Student[] FetchStudents() { LearningKOEntities dbEntities = new LearningKOEntities(); var data = (from item in dbEntities.Students orderby item.StudentId select item).Take(5); return data.ToArray(); }
/// <summary>
/// Saves Student Details
/// </summary>
/// <param name=”data”></param>
/// <returns></returns>
[WebMethod]
public static string SaveStudent(Student[] data)
{
try
{
var dbContext = new LearningKOEntities();
var studentList = from dbStududent in dbContext.Students select dbStududent;
foreach (Student userDetails in data)
{
var student = new Student();
if (userDetails != null)
{
student.StudentId = userDetails.StudentId;
student.FirstName = userDetails.FirstName;
student.LastName = userDetails.LastName;
student.Address = userDetails.Address;
student.Age = userDetails.Age;
student.Gender = userDetails.Gender;
student.Batch = userDetails.Batch;
student.Class = userDetails.Class;
student.School = userDetails.School;
student.Domicile = userDetails.Domicile;
}
Student stud=(from st in studentList where
st.StudentId==student.StudentId select st).FirstOrDefault();
if (stud == null)
dbContext.Students.Add(student);
dbContext.SaveChanges();
}
return “Data saved to database!”;
}
catch (Exception ex)
{
return “Error: “ + ex.Message;
}
}
/// <summary>
/// Deletes Student Details
/// </summary>
/// <param name=”data”></param>
/// <returns></returns>
[WebMethod]
public static string DeleteStudent(Student data)
{
try
{
var dbContext = new LearningKOEntities();
var student = dbContext.Students.FirstOrDefault
(userId => userId.StudentId == data.StudentId);
if (student != null)
{
if (student != null)
{
dbContext.Students.Remove(student);
dbContext.SaveChanges();
}
}
return “Data deleted from database!”;
}
catch (Exception ex)
{
return “Error: “ + ex.Message;
}
}
#endregion
Student
and other displaying Student
List.<table style="width:100%;" > <tbody> <tr> <th style="width:100px;">Property Name</th> <th style="width:100px;">Enter Value</th> <th style="width:100px;">Example of two Way Binding</th> </tr> </tbody> <tr> <td>Student ID (int):</td> <td> <input data-bind="value: StudentId" /> </td> <!--,valueUpdate:'keypress'--> <td><span data-bind="text: StudentId" /></td> </tr> <tr> <td>First Name :</td> <td> <input data-bind="value: FirstName" /></td> <td ><span data-bind="text: FirstName" /></td> </tr> <tr> <td>Last Name :</td> <td> <input data-bind="value: LastName" /></td> <td><span data-bind="text: LastName" /></td> </tr>
<tr>
<td>Student Age (int) :</td>
<td>
<input data-bind=”value: Age” /></td>
<td><span data-bind=”text: Age” /></td>
</tr>
<tr>
<td>Gender :</td>
<td>
<select data-bind=”options: Genders, value:
Gender, optionsCaption: ‘Select Gender…'”></select></td>
<td><span data-bind=”text: Gender” /></td>
</tr>
<tr>
<td>Batch :</td>
<td>
<input data-bind=”value: Batch” /></td>
<td><span data-bind=”text: Batch” /></td>
</tr>
<tr>
<td>Address :</td>
<td>
<input data-bind=”value: Address” /></td>
<td><span data-bind=”text: Address” /></td>
</tr>
<tr>
<td>Class :</td>
<td>
<input data-bind=”value: Class” /></td>
<td><span data-bind=”text: Class” /></td>
</tr>
<tr>
<td>School :</td>
<td>
<input data-bind=”value: School” /></td>
<td><span data-bind=”text: School” /></td>
</tr>
<tr>
<td>Domicile :</td>
<td>
<select data-bind=”options: Domiciles, value:
Domicile, optionsCaption: ‘Select Domicile…'”></select>
</td>
<td><span data-bind=”text: Domicile” /></td>
</tr>
<tr>
<td colspan=”3″>
<button type=”button” data-bind=”click:
AddStudent”>Add Student</button>
<button type=”button” data-bind=”click:
SaveStudent”>Save Student To Database</button>
</td>
</tr>
</table>
</div>
<div style=”width:70%;float:left;display:inline-block;”>
<h2>List of Students</h2>
<table style=”width:100%;” data-bind=”visible:
Students().length > 0″ border=”0″>
<tr>
<th>Student Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Gender</th>
<th>Batch</th>
<th>Address</th>
<th>Class</th>
<th>School</th>
<th>Domicile</th>
</tr>
<tbody data-bind=”foreach: Students”>
<tr>
<td><span data-bind=”text: StudentId” /></td>
<td>
<input data-bind=”value: FirstName” /></td>
<td>
<input data-bind=”value: LastName” /></td>
<td>
<input data-bind=”value: Age” /></td>
<td>
<select data-bind=”options: $root.Genders,
value: Gender”></select></td>
<td>
<input data-bind=”value: Batch” /></td>
<td>
<input data-bind=”value: Address” /></td>
<td>
<input data-bind=”value: Class” /></td>
<td>
<input data-bind=”value: School” /></td>
<td>
<select data-bind=”options: $root.Domiciles,
value: Domicile”></select></td>
<td><a href=”#” data-bind=”click: $root.
DeleteStudent”>Delete</a></td>
</tr>
</tbody>
</table>
Viewmodel
also contains observables to be bound to these properties.ViewModel
, Open the learnKO.js file and add codes to fetch, save and delete student, and observables bound to properties binded on controls of HTML page./// <reference path="jquery-2.0.3.min.js" /> /// <reference path="knockout-3.0.0.js" /> function Student(data) { this.StudentId = ko.observable(data.StudentId); this.FirstName = ko.observable(data.FirstName); this.LastName = ko.observable(data.LastName); this.Age = ko.observable(data.Age); this.Gender = ko.observable(data.Gender); this.Batch = ko.observable(data.Batch); this.Address = ko.observable(data.Address); this.Class = ko.observable(data.Class); this.School = ko.observable(data.School); this.Domicile = ko.observable(data.Domicile); }
function StudentViewModel() {
var self = this;
self.Domiciles = ko.observableArray([‘Delhi’, ‘Outside Delhi’]);
self.Genders = ko.observableArray([‘Male’, ‘Female’]);
self.Students = ko.observableArray([]);
self.StudentId = ko.observable();
self.FirstName = ko.observable();
self.LastName = ko.observable();
self.Age = ko.observable();
self.Batch = ko.observable();
self.Address = ko.observable();
self.Class = ko.observable();
self.School = ko.observable();
self.Domicile = ko.observable();
self.Gender = ko.observable();
self.AddStudent = function () {
self.Students.push(new Student({
StudentId: self.StudentId(),
FirstName: self.FirstName(),
LastName: self.LastName(),
Domicile: self.Domicile(),
Age: self.Age(),
Batch: self.Batch(),
Address: self.Address(),
Class: self.Class(),
School: self.School(),
Gender: self.Gender()
}));
self.StudentId(““),
self.FirstName(““),
self.LastName(““),
self.Domicile(““),
self.Age(““),
self.Batch(““),
self.Address(““),
self.Class(““),
self.School(““),
self.Gender(““)
};
self.DeleteStudent = function (student) {
$.ajax({
type: “POST”,
url: ‘LearnKO.aspx/DeleteStudent’,
data: ko.toJSON({ data: student }),
contentType: “application/json; charset=utf-8″,
success: function (result) {
alert(result.d);
self.Students.remove(student)
},
error: function (err) {
alert(err.status + “ – “ + err.statusText);
}
});
};
self.SaveStudent = function () {
$.ajax({
type: “POST”,
url: ‘LearnKO.aspx/SaveStudent’,
data: ko.toJSON({ data: self.Students }),
contentType: “application/json; charset=utf-8″,
success: function (result) {
alert(result.d);
},
error: function (err) {
alert(err.status + “ – “ + err.statusText);
}
});
};
$.ajax({
type: “POST”,
url: ‘LearnKO.aspx/FetchStudents’,
contentType: “application/json; charset=utf-8″,
dataType: “json”,
success: function (results) {
var students = $.map(results.d, function (item) {
return new Student(item)
});
self.Students(students);
},
error: function (err) {
alert(err.status + “ – “ + err.statusText);
}
})
}
$(document).ready(function () {
ko.applyBindings(new StudentViewModel());
});
StudentViewModel()
as our primary view model JavaScript function, that contains all the business logic and operations.applyBindings
. This initializes our view model, ko.applyBindings(new StudentViewModel());
function Student(data)
contains observables bound to model properties.observable
: Used to define model/entity properties. If these properties are bound with user interface and when value for these properties gets updated, automatically the UI elements bound with these properties will be updated with the new value instantaneously.
E.g. this.StudentId = ko.observable(“1”); - => StudentId
is the observable
property. KO represent an object for the Knockout.js library.
The value of the observable is read as var id= this. StudentId ();
observableArray
:observableArray
represents a collection of data elements which required notifications. It’s used to bind with the List kind of elements.
E.g.this.Students = ko.observableArray([]);
applyBindings
: This is used to activate knockout for the current HTML document or a specific UI element in HTML document. The parameter for this method is the view-model which is defined in JavaScript. ThisViewModel
contains theobservable
,observableArray
and various methods.
click
: Represents a click event handler added to the UI element so that JavaScript function is called.value
: This represents the value binding with the UI element’s value property to the property defined into theViewModel
.
,
,
:visible
: This is used to hide or unhide the UI element based upon the value passed to its binding.Text
: This represents the text value of the parameter passed to the UI element.
head
section of aspx page.

viewmodel
’s event.Viewmodel
’s properties.string
in StudentId
and Age
as no validation is put on those fields, code may break.


IX) Conclusion

Read more:
- C# and ASP.NET Questions (All in one)
- MVC Interview Questions
- C# and ASP.NET Interview Questions and Answers
- Web Services and Windows Services Interview Questions
Other Series
My other series of articles:
For more technical articles you can reach out to CodeTeddy.