Student Repository.cs
public Students Get(int id)
{
// Code to find a record in database
return studentList.Find(p => p.StudentsID == id);
}
public Students Add(Students item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
// Code to save record into database
item.StudentID = _nextId++;
studentList.Add(item);
return item;
}
public bool Update(Students item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
// Code to update record into database
int index = studentList.FindIndex(p => p.StudentID == item.StudentID);
if (index == -1)
{
return false;
}
studentList.RemoveAt(index);
studentList.Insert(index, item);
return true;
}
public bool Delete(int id)
{
// Code to remove the records from database
studentList.RemoveAll(p => p.StudentID == id);
return true;
}
}
IStudentRepository.cs
interface IStudentsRepository
{
Students Add(Students item);
bool Delete(int id);
Students Get(int id);
System.Collections.Generic.IEnumerable<Students> GetAll();
bool Update(Students item);
}
StudentsController.cs
static readonly IStudentRepository repository = new StudentsRepository();
//
// GET: /Students/
public ActionResult Students()
{
return View();
}
//
// GET: /Students/
public JsonResult GetAllStudents()
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
//
// GET: /Students/Create
public JsonResult CreateStudents(Students item)
{
item = repository.Add(item);
return Json(item, JsonRequestBehavior.AllowGet);
} //
// GET: /Students/Edit/
public JsonResult EditStudents(int StudentID, Students student)
{
student.StudentID = StudentID;
if (repository.Update(student))
{
return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);
}
return Json(null);
}
//
// GET: /Students/Delete/
public JsonResult Delete(int id)
{
if (repository.Delete(id))
{
return Json(new { Status = true }, JsonRequestBehavior.AllowGet);
}
return Json(new { Status = false }, JsonRequestBehavior.AllowGet);
}
Lets Create a view with Add Edit Delete
<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);
}
});
//Add New Students
self.create = function () {
if (Students.FirstName() != "" && Students.LastName() != "" && Students.City() != "" && Students.Region() != "" && Students.PostalCode() != "" && Students.Country() != "") {
$.ajax({
url: '@Url.Action("CreateStudents", "Students")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Students),
success: function (data) {
self.Students.push(data);
self.FirstName("");
self.LastName("");
self.City("");
self.Region("");
self.PostalCode("");
self.Country("");
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
}
else {
alert('Please Enter All the Values !!');
}
}
// Delete Students
self.delete = function (Students) {
if (confirm('Are you sure to Delete "' + Students.FirstName + '" student ??')) {
var id = Students.StudentsID;
$.ajax({
url: '@Url.Action("DeleteStudents", "Students")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(id),
success: function (data) {
self.Studentss.remove(Students);
// alert("Record Deleted Successfully");
}
}).fail(
function (xhr, textStatus, err) {
alert(err);
});
}
}
// Edit Students
self.edit = function (Students) {
self.Students(Students);
}
//// Update Students
self.update = function () {
var Students = self.Students();
alert(Students.StudentsID);
debugger;
$.ajax({
url: '@Url.Action("EditStudents", "Students")',
cache: false,
type: 'PUT',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(Students),
success: function (data) {
alert(data);
self.Studentss.removeAll();
self.Studentss(data); //Put the response in ObservableArray
self.Students(null);
alert("Record Updated Successfully");
}
})
.fail(
function (xhr, textStatus, err) {
alert(err);
});
}
$(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>
Conclusion So far in this article we have learned how to Edit Add Delete records using Knockout.js in MVC5
Reference