Edit,Add,Delete Data Using Knockout in MVC 5

Rama Sagar
Posted by in ASP.NET MVC category on for Beginner level | Points: 250 | Views : 24498 red flag
Rating: 5 out of 5  
 1 vote(s)

Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates.For more info http://en.wikipedia.org/wiki/KnockoutJS

Introduction

This article explains how to add edit delete data using Knockout.js in MVC5..

Please have a look at my previous article as this is the continuation  of that 

Lets make a few changes in Student Repository

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


Page copy protected against web site content infringement by Copyscape

About the Author

Rama Sagar
Full Name: RamaSagar Pulidindi
Member Level: Silver
Member Status: Member,MVP
Member Since: 12/30/2012 1:51:40 AM
Country: India
ramasagar
http://www.ramasagar.com
A Software Profesional working in Microsoft .NET technologies since year 2008, and I work for Dake ACE. I am passionate about .NET technology and love to contribute to the .NET community at Dot Net Funda

Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 11/4/2013 | Points: 25
Thanks for the nice explanations Ram Sagar, a screen shot of the output would have added charm to this article and would have easy for readers to visualize how the final output would look like.

Thanks and keep it up!

Posted by: Ermahesh2009 on: 4/28/2014 | Points: 25
is this code applicable to MVC4 as Well ?

Login to post response

Comment using Facebook(Author doesn't get notification)