Click here to Skip to main content
11,929,283 members (58,492 online)
Click here to Skip to main content
Add your own
alternative version


1 download
20 bookmarked

Customer KnockoutJS and MVC demo using JSON

, 19 Jul 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Customer KnockoutJS and MVC demo using JSON.

After reading about KnockoutJS I have decided to create a simple demo using JSON to comunicate with the web server. The application retrieves a Customer from an ASP.NET MVC Action and sends it to be saved.

The KnockoutJS is a JavaScript Model View ViewModel (MVVM) framework. The View Model object contains properties which values are specified as ko.observable(). Knockout will automatically updates the UI when the view model changes. KnockoutJS has a declarative binding syntax where the HTML view elements are bind with our view model object. Knockout uses the "data-bind" attribute in the HTML elements for the data binding.

To learn the basics, go to the KnockoutJS site by pressing here.


The ASP.NET MVC Controller have the actions to Get and Add a customer.

namespace KnockoutDemo.Controllers
    public class HomeController : Controller
        public ActionResult Index()
            ViewBag.Message = "";
            return View();

        public JsonResult Get(int customerID)
            // Get the customer ...
            Customer customer = new Customer {CustomerID = customerID, 
              FirstName = "John", LastName = "Doe", IsMale = true };

            return Json(customer);

        public JsonResult Add(Customer customer)
            // Save the customer ...

            // return status message 
            var message = "Customer: " + customer.FirstName + " " + customer.LastName + " Added.";
            message += " IsMale: " + customer.IsMale.ToString();
            return Json(message);


The ASP.NET MVC model is the customer:

public class Customer
    public int CustomerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsMale { get; set; }

The ASP.NET MVC Layout:

<!DOCTYPE html>
    <meta charset="utf-8" />
    <link href="@Url.Content("~/Content/Site.css")" 
        rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" 
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" 
    <script src="@Url.Content("~/Scripts/knockout.js")" 
    <script src="@Url.Content("~/Scripts/json2.js")" 
    <script src="@Url.Content("~/Scripts/knockout.validation.js")" 
    <div class="page">
            <div id="title">
                <h1>Knockout Demo</h1>
        <section id="main">

And finally the ASP.NET MVC view has the KnockoutJS specifics:

    ViewBag.Title = "Add Customer";

<form action="" method="post">
  Customer Number:  <span data-bind="text: CustomerID"></span>
  First Name: <input data-bind="value: FirstName" style="width: 200px;" type="text" /> 
  Last Name: <input data-bind="value: LastName" style="width: 200px;" type="text" /> 
  <input data-bind="checked: IsMale" type="checkbox" />Male
  <input data-bind="click: KnockoutDemoNamespace.addCustomer" type="button" value="Add Customer" />
<script type="text/javascript">
// Initialized the namespace
var KnockoutDemoNamespace = {};

// View model declaration
KnockoutDemoNamespace.initViewModel= function(customer) {
    var customerViewModel = {
        CustomerID: ko.observable(customer.CustomerID),
        FirstName: ko.observable(customer.FirstName),
        LastName: ko.observable(customer.LastName),
        IsMale: ko.observable(customer.IsMale)
    return customerViewModel;

// Bind the customer
KnockoutDemoNamespace.bindData = function(customer)
    // Create the view model
    var viewModel = KnockoutDemoNamespace.initViewModel(customer);


KnockoutDemoNamespace.getCustomer = function (customerID) {

        url: "/Home/Get/",
        type: 'post',
        data: "{'customerID':'1' }",
        contentType: 'application/json',
        success: function (result) {
        error: function (jqXHR, textStatus, errorThrown) {
            var errorMessage = '';

KnockoutDemoNamespace.addCustomer = function () {
            url: "/Home/Add/",
            type: 'post',
            data: ko.toJSON(this),
            contentType: 'application/json',
            success: function (result) {


    $(document).ready(function () {


The KnockoutJS has the following specifics:

  1. View Model object: customerViewModel
  2. HTML View: The HTML from the page with the KnockoutJS specific attributes for data binding
  3. The demo performs a data bind with a span, and the input types text, checkbox and button. Note that the "data-bind" has the html element attribute to be affected and the View Model property associated.

  4. View Model activation: ko.applyBindings(viewModel);


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


About the Author

Rui Inacio
Team Leader
Portugal Portugal
I am an Experienced Senior Microsoft Consultant responsible for developing and defining architectures for various projects in a Microsoft environment, using a Service-Oriented Architecture (SOA) and web based applications.
I am also a project manager using agile methodologies and SCRUM.
Software Quality Assurance is a mandatory in every project I am responsible.
As someone said:
“Anyone can program, but not everyone is a programmer...”

You may also be interested in...

Comments and Discussions

QuestionDynamically Asigning Values to model & adding them to List<>..... instead of Hard Coding Pin
sunny182424-Jan-13 18:58
membersunny182424-Jan-13 18:58 
GeneralMy vote of 1 Pin
chakaloso4-Dec-12 14:26
memberchakaloso4-Dec-12 14:26 
GeneralRe: My vote of 1 Pin
Rui Inacio5-Dec-12 0:11
memberRui Inacio5-Dec-12 0:11 
QuestionThank you very much! Pin
Pikesville Paesano27-Nov-12 17:00
memberPikesville Paesano27-Nov-12 17:00 
GeneralMy vote of 5 Pin
RupeshKumar24-Jul-12 6:41
memberRupeshKumar24-Jul-12 6:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 19 Jul 2012
Article Copyright 2012 by Rui Inacio
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid