Click here to Skip to main content
Click here to Skip to main content

Knockout JS - Add, update and delete records

, 18 Jun 2014
Rate this:
Please Sign up or sign in to vote.
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

var candidateArray = [];

var candidateRowNumber = 0;

//ready function

$(document).ready(function () {        

   fillCandidates();

});

function fillCandidates() {   

        var emptyVal = '';     

        //Apply bindings for new candidate      

            var initData = [];

            var viewModel = new CandidateViewModel();

            var candidatedata = new candidateDetail(0,emptyVal, emptyVal,0);

            viewModel.parentCandidate(candidatedata);

            viewModel.candidateDetails(initData);

            try {                

                ko.applyBindings(viewModel, document.getElementById('dvcandidate'));

            }

            catch (e) { }   

};

    function CandidateViewModel() {

        var self = this;

        var emptyVal = '';

        self.candidateDetails = ko.observableArray([]);

        self.parentCandidate = ko.observable("");      

        //functionality to identify whether to add or edit skill

        self.AddEditCandidateRow = function () {            

                if (self.parentCandidate().rowNumber() == 0) {

                    candidateRowNumber++;

                    var editcandidateArray = [];                   

                    candidateArray.push(new candidateDetail(self.parentCandidate().id(), self.parentCandidate().Name(), self.parentCandidate().Address(), candidateRowNumber));                  

                    self.candidateDetails(candidateArray);

                }

                else {

                    $.each(self.candidateDetails(), function () {

                        if (this.rowNumber() == self.parentCandidate().rowNumber()) {

                            this.id(self.parentCandidate().id());

                            this.Name(self.parentCandidate().Name());

                            this.Address(self.parentCandidate().Address());                           

                            this.rowNumber(self.parentCandidate().rowNumber());

                        }

                    });

                }

                self.parentCandidate(new candidateDetail(0, emptyVal, emptyVal, 0));            

        };  

        self.editCandidateRow = function (num) {

            $.each(self.candidateDetails(), function () {

                if (this.rowNumber() == num()) {

                    self.parentCandidate(new candidateDetail(this.id(), this.Name(), this.Address(), this.rowNumber()));

                }

            });

        };

        self.deleteCandidateRow = function (can) {                   

            if (confirm('Are you sure to delete Candidate Details?')) {              

                self.candidateDetails.remove(can);              

                candidateRowNumber--;              

            };

        }.bind(self);

    };   

    //View model for skill popup

    function candidateDetail(id, Name, Address, rowNumber) {

        var self = this;

        self.id = ko.observable(id);

        self.Name = ko.observable(Name);

        self.Address = ko.observable(Address);      

        self.rowNumber = ko.observable(rowNumber);          

    };

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:

@{

    ViewBag.Title = "Tutorial1";

}

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

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

<script src="~/Scripts/Tutorial1.js"></script>

<h2>Knockout js Add, Update and Delete Records</h2>

<div id="dvcandidate">  

    <div>

        <h2>Candidate</h2>

    </div>

    <div id="dvaddcandidate">

    <table>

        <thead>

            <tr>

                <td colspan="2">Add New Candidate</td>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>Name</td>

                <td><input data-bind="value: parentCandidate().Name" type="text" id="txtcandidatename" /></td>

            </tr>

            <tr>

                <td>Address</td>

                <td><input data-bind="value: parentCandidate().Address" type="text" id="txtcandidateaddress" /></td>

            </tr>

            <tr>

                <td colspan="2" style="float:right;"><input type="button" data-bind="event:{click: AddEditCandidateRow}" id="btnaddcandidaterow" value="Add" /></td>

            </tr>

        </tbody>

    </table>

        </div>

    <div id="dvcandidatelisting">

                    <table>

                <thead>

                    <tr>

                        <th>Name</th>

                        <th>Address</th>                    

                        <th>&nbsp;</th>

                    </tr>

                </thead>

                <tbody data-bind="foreach: candidateDetails">

                    <tr>

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

                        <td><label data-bind="text: Address"></label></td>                        

                        <td>                     

                             <a href="javascript:void(0);" data-bind="event:{click: $root.editCandidateRow.bind($data,rowNumber)}">Edit</a>

                             <a href="javascript:void(0);" data-bind="click: $root.deleteCandidateRow">Delete</a>

                        </td>

                    </tr>

                </tbody>

            </table>

    </div>

</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)

About the Author

ashish_5437
Software Developer (Senior)
India India
Developing projects and web applications for more than 6 years.

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 18 Jun 2014
Article Copyright 2014 by ashish_5437
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid