• Introduction:
  • In this article we will learn how to use foreach binding in KnockoutJS or what is foreach binding in KnockoutJS or why use foreach binding in KnockoutJS with example.
  • Description:
  • KnockoutJS  foreach bindings basically used to repeat html markup according to the number of elements in an observable array . This is very useful for display a list or table format data. if you have an observable array, adding or removing elements from the array it will automatically reflect in the html markup. If you add an element will add html markup for the element and removing an element shall automatically remove html markup.   

Let’s see a simple example of knockoutJS foreach binding.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="foreachBinding.aspx.cs"
    Inherits="AspDotNet.foreachBinding" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <script src="Scripts/jquery-3.1.1.min.js"></script>
    <script src="Scripts/knockout-3.4.2.js"></script>
    <form id="form1" runat="server">
    <table style="width:400px; border:1px solid;" border="1">
            <tr><th>Employee Name</th><th>Salary</th></tr>
        <tbody data-bind="foreach: Employees">
                <td data-bind="text: EmployeeName"></td>
                <td data-bind="text: salary"></td>
    <script type="text/javascript">
        function AppViewModel() {
            var self = this;
            self.Employees =ko.observableArray([
                { EmployeeName: 'Bert john',salary:10000 },
                { EmployeeName: 'Charles mark',salary:30000},
                { EmployeeName: 'Denise bhargo',salary: 20000 }
        ko.applyBindings(new AppViewModel());



How to use foreach binding in KnockoutJS

The above code. we declare an observableArray named Employees. Each item in an array is an object written in JSON format. Each object has EmployeeName and Salary parameter. There are 3 objects in total.

Now come to the html view section. Here we have created a table to show the EmployeeName and salary parameter from the objects in Employees array. Notice that the foreach binding is used with the “tbody” tag which means that whatever is inside this tag shall be repeated the number of times the elements in the Employees array. Also, during each iteration the values for EmployeeName and Salary parameters shall be displayed within the tag.



 I hope this article will help to you.


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like