<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/knockout-2.2.0.js"></script>
<script src='@Url.Content("~/Scripts/knockout-2.2.0.debug.js")' type="text/javascript"></script>
<script type="text/javascript">
function StudentsViewModel() {
var self = this;
//Declare observable
self.StudentID = ko.observable("");
self.FirstName = ko.observable("");
self.LastName = ko.observable("");
self.City = ko.observable("");
self.Region = ko.observable("");
self.PostalCode = ko.observable("");
self.Country = ko.observable("");
var Students= {
StudentID: self.StudentID,
FirstName: self.FirstName,
LastName: self.LastName,
City: self.City,
Region: self.Region,
PostalCode: self.PostalCode,
Country: self.Country
};
self.student = ko.observable();
self.Students = ko.observableArray();
// Initialize the view-model
$.ajax({
url: '@Url.Action("GetAllStudents", "Students")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
self.Students(data);
}
});
$(document).ready(function () {
var viewModel = new StudentsViewModel();
ko.applyBindings(viewModel);
});
}
</script>
<h3>
Students List</h3>
<table id="empl" data-bind="visible: Studnets().length > 0">
<thead>
<tr>
<th>
Student ID
</th>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
City
</th>
<th>
Region
</th>
<th>
Postal Code
</th>
<th>
Country
</th>
</tr>
</thead>
<tbody data-bind="foreach: Students">
<tr>
<td data-bind="text: StudnetID">
</td>
<td data-bind="text: FirstName">
</td>
<td data-bind="text: LastName">
</td>
<td data-bind="text: City">
</td>
<td data-bind="text: Region">
</td>
<td data-bind="text: PostalCode">
</td>
<td data-bind="text: Country">
</td>
<td>
<button data-bind="click: $root.Remove">
Remove</button>
</td>
</tr>
</tbody>
</table>
In this article we have learned how to work with Knockout.js and display data using Knockout.js