Add, Edit, Delete Data Using Knockout in MVC 4

In this article you will see how to add a new record, delete and edit data using Knockout in MVC 4.

In my last article we saw how to display data using Knockout using MVC 4 here. Now in this article you will see how to add a new record, delete and edit data using Knockout in MVC 4.

Read my first article about how to start and how to display data. In this article we will learn only how to add a new record, delete a record and edit a record.

Do this in my model class.

public class Employee
{
    public int EmployeeID { get; set; }
   
public string LastName { get; set; }
   
public string FirstName { get; set; }
    
public string City { get; set; }
   
public string Region { get; set; }
   
public string PostalCode { get; set; }
   
public string Country { get; set; }
}


This is the repository class; as you can see this class is inherited by the interface so the interface code is below this.

public class EmployeeRepository : KnockoutSample.Models.IEmployeeRepository

    {

        private List<Employee> employeeList = new List<Employee>();

        private int _nextId = 1;

 

        public EmployeeRepository()

        {

            // Add employees records to display

            Add(new Employee { EmployeeID = 1, FirstName = "Nancy", LastName = "Davolio", City = "Seattle", Region = "WA", PostalCode = "98122", Country = "USA" });

            Add(new Employee { EmployeeID = 2, FirstName = "Andrew", LastName = "Fuller", City = "Tacoma", Region = "WA", PostalCode = "98401", Country = "USA" });

            Add(new Employee { EmployeeID = 3, FirstName = "Janet", LastName = "Leverling", City = "Kirkland", Region = "WA", PostalCode = "98033", Country = "USA" });

            Add(new Employee { EmployeeID = 4, FirstName = "Margaret", LastName = "Peacock", City = "Redmond", Region = "WA", PostalCode = "98052", Country = "USA" });

            Add(new Employee { EmployeeID = 5, FirstName = "Steven", LastName = "Buchanan", City = "London", Region = "WA", PostalCode = "SW1 8JR", Country = "UK" });

            Add(new Employee { EmployeeID = 6, FirstName = "Michael", LastName = "Suyama", City = "London", Region = "WA", PostalCode = "EC2 7JR", Country = "UK" });

            Add(new Employee { EmployeeID = 7, FirstName = "Robert", LastName = "King", City = "London", Region = "WA", PostalCode = "RG1 9SP", Country = "UK" });

            Add(new Employee { EmployeeID = 8, FirstName = "Laura", LastName = "Callahan", City = "Seattle", Region = "WA", PostalCode = "98105", Country = "USA" });

            Add(new Employee { EmployeeID = 9, FirstName = "Anne", LastName = "Dodsworth", City = "London", Region = "WA", PostalCode = "WG2 7LT", Country = "UK" });

           

        }

 

        public IEnumerable<Employee> GetAll()

        {

            // Code to get the list of all the records in database

            return employeeList;

        }

 

        public Employee Get(int id)

        {

            // Code to find a record in database

            return employeeList.Find(p => p.EmployeeID == id);

        }

 

        public Employee Add(Employee item)

        {

            if (item == null)

            {

                throw new ArgumentNullException("item");

            }

 

            // Code to save record into database

            item.EmployeeID = _nextId++;

            employeeList.Add(item);

 

            return item;

        }

 

        public bool Update(Employee item)

        {

            if (item == null)

            {

                throw new ArgumentNullException("item");

            }

 

            // Code to update record into database

            int index = employeeList.FindIndex(p => p.EmployeeID == item.EmployeeID);

            if (index == -1)

            {

                return false;

            }

            employeeList.RemoveAt(index);

            employeeList.Insert(index, item);

 

            return true;

        }

 

        public bool Delete(int id)

        {

            // Code to remove the records from database

            employeeList.RemoveAll(p => p.EmployeeID == id);

 

            return true;

        }

 

    }

And this is the repository interface.

interface IEmployeeRepository

    {

        Employee Add(Employee item);

        bool Delete(int id);

        Employee Get(int id);

        System.Collections.Generic.IEnumerable<Employee> GetAll();

        bool Update(Employee item);

    }

And this is the repository interface.

static readonly IEmployeeRepository repository = new EmployeeRepository();

        //

        // GET: /Employee/

        public ActionResult Employee()

        {

            return View();

        }

        //

        // GET: /Employees/

        public JsonResult GetAllEmployees()

        {

            return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);

        }           

        //

        // GET: /Employee/Create

        public JsonResult CreateEmployee(Employee item)

        {

            item = repository.Add(item);

            return Json(item, JsonRequestBehavior.AllowGet);

        }         //

        // GET: /Employee/Edit/5

        public JsonResult EditEmployee(int EmployeeID, Employee employee)

        {

            employee.EmployeeID = EmployeeID;

            if (repository.Update(employee))

            {

                return Json(repository.GetAll(), JsonRequestBehavior.AllowGet);

            }

            return Json(null);

        }

        //

        // GET: /Employee/Delete/5

        public JsonResult Delete(int id)

        {

            if (repository.Delete(id))

            {

                return Json(new { Status = true }, JsonRequestBehavior.AllowGet);

            }

            return Json(new { Status = false }, JsonRequestBehavior.AllowGet);

        }

Now let's work on views.
 

<script src="~/Scripts/jquery-2.0.3.js"></script>

    <script src="~/Scripts/knockout-2.3.0.js" ></script>

    <script src='@Url.Content("~/Scripts/knockout-2.3.0.debug.js")'  type="text/javascript"></script>

    <script type="text/javascript">

        function EmployeeViewModel()

{          

            var self = this;

            self.EmployeeID = 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 Employee = {

                EmployeeID: self.EmployeeID,

                FirstName: self.FirstName,

                LastName: self.LastName,

                City: self.City,

                Region: self.Region,

                PostalCode: self.PostalCode,

                Country: self.Country

            };

 

            self.Employee = ko.observable();

            self.Employees = ko.observableArray();  

       

             $.ajax({

                url: '@Url.Action("GetAllEmployees", "Employee")',

                cache: false,

                type: 'GET',

                contentType: 'application/json; charset=utf-8',

                data: {},

                success: function (data) {                  

                    self.Employees(data);

                }

            });

 

            //Add New Employee

            self.create = function () {               

                if (Employee.FirstName() != "" && Employee.LastName() != "" && Employee.City() != "" && Employee.Region() != "" && Employee.PostalCode() != "" && Employee.Country() != "") {

                    $.ajax({

                        url: '@Url.Action("CreateEmployee", "Employee")',

                    cache: false,

                    type: 'POST',

                    contentType: 'application/json; charset=utf-8',

                    data: ko.toJSON(Employee),

                    success: function (data) {                       

                        self.Employees.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 employee

        self.delete = function (Employee) {

            if (confirm('Are you sure to Delete "' + Employee.FirstName + '" employee ??')) {

                var id = Employee.EmployeeID;

 

                $.ajax({

                    url: '@Url.Action("DeleteEmployee", "Employee")',

                        cache: false,

                        type: 'POST',

                        contentType: 'application/json; charset=utf-8',

                        data: ko.toJSON(id),

                        success: function (data) {

                            self.Employees.remove(Employee);

                            //   alert("Record Deleted Successfully");

                        }

                    }).fail(

                     function (xhr, textStatus, err) {

                         alert(err);

                     });

                    }

            }

 

            // Edit employee

                self.edit = function (Employee) {

                    self.Employee(Employee);

 

                }

 

            //// Update employee

           self.update = function () {

                    var Employee = self.Employee();

                    alert(Employee.EmployeeID);

                   

                    debugger;

                    $.ajax({

                        url: '@Url.Action("EditEmployee", "Employee")',

                        cache: false,

                        type: 'PUT',

                        contentType: 'application/json; charset=utf-8',

                        data: ko.toJSON(Employee),                       

                        success: function (data) {

                            alert(data);

                            self.Employees.removeAll();

                            self.Employees(data); //Put the response in ObservableArray

                            self.Employee(null);

                            alert("Record Updated Successfully");

 

                        }

                    })

                .fail(

                function (xhr, textStatus, err) {

                    alert(err);

                });

                }

 

 

            // Reset employee

                self.reset = function () {

                    self.FirstName("");

                    self.LastName("");

                    self.City("");

                    self.Region("");

                    self.PostalCode("");

                    self.Country("");

                }

 

            // Cancel employee

 

                self.cancel = function () {

                    self.Employee(null);

 

                }

         }     

 

            // Binding knockout

 

        $(document).ready(function () {

            var viewModel = new EmployeeViewModel();           

            ko.applyBindings(viewModel);

        });

    </script>

 

<h3>Employees</h3>

    <table id="empl" data-bind="visible: Employees().length > 0">

        <thead>

            <tr>

                <th>Employee 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: Employees">

            <tr>

                <td data-bind="text: EmployeeID"></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.edit">Edit</button>

                    <button data-bind="click: $root.delete">Delete</button>

 

                </td>

 

            </tr>

        </tbody>       

    </table>

    <br />

    <div style="border-top: solid 2px  #282828; width: 430px; height: 10px">&nbsp;</div>

 <div data-bind="if: Employee">

        <div>

            <h2>Update Employee</h2>

        </div>

        <div>

            <label for="EmployeeID" data-bind="visible: false">Employee ID</label>

            <label data-bind="text: Employee().EmployeeID, visible: false"></label>

 

        </div>

        <div>

            <label for="firstname">First Name</label>

            <input data-bind="value: Employee().FirstName" type="text" title="First Name" />

        </div>

 

        <div>

            <label for="lastname">Last Name</label>

            <input data-bind="value: Employee().LastName" type="text" title="Last Name" />

        </div>

 

        <div>

            <label for="city">City</label>

            <input data-bind="value: Employee().City" type="text" title="City" />

        </div>

 

        <div>

            <label for="region">Region</label>

            <input data-bind="value: Employee().Region" type="text" title="Price" />

 

        </div>

 

        <div>

            <label for="postalcode">Postal Code</label>

            <input data-bind="value: Employee().PostalCode" type="text" title="PostalCode" />

 

        </div>

        <div>

            <label for="country">Country</label>

            <input data-bind="value: Employee().Country" type="text" title="Country" />

 

        </div>

        <br />

        <div>

            <button data-bind="click: $root.update">Update</button>

            <button data-bind="click: $root.cancel">Cancel</button>

 

        </div>

    </div>

 

    <div data-bind="ifnot: Employee()">

        <div>

            <h2>Add New Employee</h2>

        </div>

        <div>

            <label for="firstname">First Name</label>

            <input data-bind="value: $root.FirstName" type="text" title="FirstName" />

        </div>

 

         <div>

            <label for="lastname">Last Name</label>

            <input data-bind="value: $root.LastName" type="text" title="LastName" />

        </div>

 

        <div>

            <label for="city">City</label>

            <input data-bind="value: $root.City" type="text" title="City" />

        </div>

 

        <div>

            <label for="region">Region</label>

            <input data-bind="value: $root.Region" type="text" title="Region" />

        </div>

 

         <div>

            <label for="postalcode">Postal Code</label>

            <input data-bind="value: $root.PostalCode" type="text" title="PostalCode" />

        </div>

 

         <div>

            <label for="country">Country</label>

            <input data-bind="value: $root.Country" type="text" title="Country" />

        </div>

        <br />

        <div>

            <button data-bind="click: $root.create">Save</button>

            <button data-bind="click: $root.reset">Reset</button>

 

        </div>

    </div>

Hit F5 to run the application.

Knockout in MVC 4

Image 1.