Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Knockout JS - Add, update and delete records

4.00/5 (2 votes)
18 Jun 2014CPOL7 min read 21.5K   21  
This section explains the add, edit and delete records using knockout js.

Introduction

This section explains how to add records to knockout observable array and show these to list and after adding records to list how to edit/delete these records.

Working implementation of the same can be found on below js fiddle url:

http://jsfiddle.net/ashish_786/Nj3Vm/embedded/result/

Background

To understand this article basic knowledge of following is necessary:

1. Asp.net MVC

2. Knockout JS

3. Jquery

Using the code

Here i am going to implement the add, edit and delete operations in knockout js and to implement the same, very first i create the model for candidate named as 'candidateDetail'. With this model all properties of candidate is assigned by observable variables. After creates the candidate model i created the viewModel containing the required observable variables, observable arrays and events and finally do 'apply bindings' in ready function. These all js view model implementation can be found as below:

--- JS FILE:

//variables<br />
var candidateArray = [];<br />
var candidateRowNumber = 0;<br />
//ready function<br />
$(document).ready(function () {        <br />
   fillCandidates();<br />
});<br />
function fillCandidates() {   <br />
        var emptyVal = '';     <br />
        //Apply bindings for new candidate      <br />
            var initData = [];<br />
            var viewModel = new CandidateViewModel();<br />
            var candidatedata = new candidateDetail(0,emptyVal, emptyVal,0);<br />
            viewModel.parentCandidate(candidatedata);<br />
            viewModel.candidateDetails(initData);<br />
            try {                <br />
                ko.applyBindings(viewModel, document.getElementById('dvcandidate'));<br />
            }<br />
            catch (e) { }   <br />
};<br />
    function CandidateViewModel() {<br />
        var self = this;<br />
        var emptyVal = '';<br />
        self.candidateDetails = ko.observableArray([]);<br />
        self.parentCandidate = ko.observable("");      <br />
        //functionality to identify whether to add or edit skill<br />
        self.AddEditCandidateRow = function () {            <br />
                if (self.parentCandidate().rowNumber() == 0) {<br />
                    candidateRowNumber++;<br />
                    var editcandidateArray = [];                   <br />
                    candidateArray.push(new candidateDetail(self.parentCandidate().id(), self.parentCandidate().Name(), self.parentCandidate().Address(), candidateRowNumber));                  <br />
                    self.candidateDetails(candidateArray);<br />
                }<br />
                else {<br />
                    $.each(self.candidateDetails(), function () {<br />
                        if (this.rowNumber() == self.parentCandidate().rowNumber()) {<br />
                            this.id(self.parentCandidate().id());<br />
                            this.Name(self.parentCandidate().Name());<br />
                            this.Address(self.parentCandidate().Address());                           <br />
                            this.rowNumber(self.parentCandidate().rowNumber());<br />
                        }<br />
                    });<br />
                }<br />
                self.parentCandidate(new candidateDetail(0, emptyVal, emptyVal, 0));            <br />
        };  <br />
        self.editCandidateRow = function (num) {<br />
            $.each(self.candidateDetails(), function () {<br />
                if (this.rowNumber() == num()) {<br />
                    self.parentCandidate(new candidateDetail(this.id(), this.Name(), this.Address(), this.rowNumber()));<br />
                }<br />
            });<br />
        };<br />
        self.deleteCandidateRow = function (can) {                   <br />
            if (confirm('Are you sure to delete Candidate Details?')) {              <br />
                self.candidateDetails.remove(can);              <br />
                candidateRowNumber--;              <br />
            };<br />
        }.bind(self);<br />
    };   <br />
    //View model for skill popup<br />
    function candidateDetail(id, Name, Address, rowNumber) {<br />
        var self = this;<br />
        self.id = ko.observable(id);<br />
        self.Name = ko.observable(Name);<br />
        self.Address = ko.observable(Address);      <br />
        self.rowNumber = ko.observable(rowNumber);          <br />
    };

Based on the bindings and view model created in js file, I prepared mvc view. In the mvc view i created placeholders with bindings to enter candidate details and a functionality to save details. After adding candidate details, these details will start reflecting in the listing.

The html with knockout bindings in MVC view is following:

@{<br />
    ViewBag.Title = "Tutorial1";<br />
}<br />
<script src="~/Scripts/jquery-1.7.1.js"></script><br />
<script src="~/Scripts/knockout-2.1.0.js"></script><br />
<script src="~/Scripts/Tutorial1.js"></script><br />
<h2>Knockout js Add, Update and Delete Records</h2><br />
<div id="dvcandidate">  <br />
    <div><br />
        <h2>Candidate</h2><br />
    </div><br />
    <div id="dvaddcandidate"><br />
    <table><br />
        <thead><br />
            <tr><br />
                <td colspan="2">Add New Candidate</td><br />
            </tr><br />
        </thead><br />
        <tbody><br />
            <tr><br />
                <td>Name</td><br />
                <td><input data-bind="value: parentCandidate().Name" type="text" id="txtcandidatename" /></td><br />
            </tr><br />
            <tr><br />
                <td>Address</td><br />
                <td><input data-bind="value: parentCandidate().Address" type="text" id="txtcandidateaddress" /></td><br />
            </tr><br />
            <tr><br />
                <td colspan="2" style="float:right;"><input type="button" data-bind="event:{click: AddEditCandidateRow}" id="btnaddcandidaterow" value="Add" /></td><br />
            </tr><br />
        </tbody><br />
    </table><br />
        </div><br />
    <div id="dvcandidatelisting"><br />
                    <table><br />
                <thead><br />
                    <tr><br />
                        <th>Name</th><br />
                        <th>Address</th>                    <br />
                        <th>&nbsp;</th><br />
                    </tr><br />
                </thead><br />
                <tbody data-bind="foreach: candidateDetails"><br />
                    <tr><br />
                        <td><label data-bind = "text: Name"></label></td><br />
                        <td><label data-bind="text: Address"></label></td>                        <br />
                        <td>                     <br />
                             <a href="javascript:void(0);" data-bind="event:{click: $root.editCandidateRow.bind($data,rowNumber)}">Edit</a><br />
                             <a href="javascript:void(0);" data-bind="click: $root.deleteCandidateRow">Delete</a><br />
                        </td><br />
                    </tr><br />
                </tbody><br />
            </table><br />
    </div><br />
</div>

In the div (id='dvaddcandidate'), i added placeholders(input fields) with knockout bindings for entering candidate details, while entering candidate details these details are assigning to observable variables by knockout bindings and on click of Add button this Candidate object will add to observable Array(Array of candidate object).

To show the contents of this array i used foreach bindings in 2nd table to display candidate details. Within foreach binding the candidate detail can be output with syntax:

<label data-bind = "text: Name"></label>

Hope above contents help you all to implement the functionality!

Points of Interest

Knockout js, jquery, MVC..

History

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)