Introductory examples

Detailed examples

Grid editor example

An example of using the ‘foreach’ binding to render content for each item in an array. When you add or remove items, Knockout doesn’t need to re-render everything - it only renders the appropriate elements for the new item. The means the state of other rich UI controls (e.g., validators) isn’t wiped out.

For a detailed step-by-step tutorial about building this example and integrating it with ASP.NET MVC, see this blog post.

Live example

You have asked for   gift(s)

Gift name Price

Source code: View

<form action='/someServerSideHandler'>
    <p>You have asked for <span data-bind='text: gifts().length'>&nbsp;</span> gift(s)</p>
    <table data-bind='visible: gifts().length > 0'>
                <th>Gift name</th>
                <th />
        <tbody data-bind='foreach: gifts'>
                <td><input class='required' data-bind='value: name, uniqueName: true' /></td>
                <td><input class='required number' data-bind='value: price, uniqueName: true' /></td>
                <td><a href='#' data-bind='click: $root.removeGift'>Delete</a></td>

    <button data-bind='click: addGift'>Add Gift</button>
    <button data-bind='enable: gifts().length > 0' type='submit'>Submit</button>

Source code: View model

var GiftModel = function(gifts) {
    var self = this; = ko.observableArray(gifts);

    self.addGift = function() {{
            name: "",
            price: ""

    self.removeGift = function(gift) {;
    }; = function(form) {
        alert("Could now transmit to server: " + ko.utils.stringifyJson(;
        // To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0],;

var viewModel = new GiftModel([
    { name: "Tall Hat", price: "39.95"},
    { name: "Long Cloak", price: "120.00"}

// Activate jQuery Validation
$("form").validate({ submitHandler: });

Try it in jsFiddle