Using Knockout With Razor Web Pages In WebMatrix 2

4.69 (13 votes)

Knockout is an increasingly popular JavaScript UI library. Its popularity is likely to increase among ASP.NET developers soon as it comes as part of some of the new MVC 4 site templates. This article looks at what Knockout is, what problems it is intended it solve and how to use it in an ASP.NET Razor Web Pages site built in WebMatrix.

Knockout was inspired by the Model-View-ViewModel (MVVM) pattern that's popular with Silverlight and WPF developers. It is intended to help keep UI fabric (HTML etc) and data separated and to make is it easier to build rich user interfaces through a declarative data binding system. At its core is the View Model, or a representation of the data that your page or "View" will use. Knockout's real strength lies in its ability to track changes in the view model's values, and apply those changes to any dependencies as well as automatically propagate those changes to the UI.

OK, great - but what's all that in plain English? Hmmm. Probably easiest to explain through example.

The sample application will allow a user to select a category from the Northwind database and view all products associated with that category. They will be able to select individual products and view more details for that chosen product, including the number of units in stock. They will be able to buy a unit, and the total units in stock will reduce accordingly. All of this will happen in one page, with no full postbacks. The site will use jQuery, although Knockout does not require it. I have used WebMatrix 2 RC, which means that I was able to obtain both jQuery and Knockout from the new Nuget integration:

The layout page code contains references to both libraries, an optional RenderSection call for additional scripts and some minimal styling:

<!DOCTYPE html>

<html lang="en">
        <meta charset="utf-8" />
            body{font-size: 85%; font-family:"Segoe UI", Arial, Helvetica;}
            #products{float:left; width:300px;}
            .label{float:left;width:120px;padding-right:5px;text-align:right; font-weight:bold;}
        <script src="~/Scripts/jquery-1.7.2.min.js"></script>
        <script src="~/Scripts/knockout-2.1.0.js"></script>
        @RenderSection("script", required: false)

One other Razor 2 thing to notice is the new cleaner Url resolution mechanism that means you do not need to use the Href helper anymore. Razor knows that ~/ represents the root of the site. The layout page is specified in a _PageStart.cshtml file in the root of the site.

The data for the application will be provided as JSON using the JSON helper. Three sets of data are required according to the functional requirement outlined above: a list of categories (GetCategories.cshtml), a list of products by category (GetProductsByCategory.cshtml) and details of a specific product (GetProductById.cshtml). The 3 separate files are placed in a folder called JsonService:


    var db = Database.Open("Northwind");
    var sql = "SELECT CategoryId, CategoryName FROM Categories";
    var data = db.Query(sql);
    Response.ContentType = "application/json";
    Json.Write(data, Response.Output);



    if (UrlData[0].IsEmpty() || !UrlData[0].IsInt()) {
    var db = Database.Open("Northwind");
    var sql = "SELECT ProductId, ProductName From Products Where CategoryId = @0";
    var data = db.Query(sql, UrlData[0]);
    if(data.Count() == 0){
    Response.ContentType = "application/json";
    Json.Write(data, Response.Output);



    if (UrlData[0].IsEmpty() || !UrlData[0].IsInt()) {
    var db = Database.Open("Northwind");
    var sql = @"SELECT ProductId, ProductName, ContactTitle, ContactName, 
                CompanyName, QuantityPerUnit, UnitPrice, UnitsInStock
                FROM Products INNER JOIN Suppliers
                ON Products.SupplierID = Suppliers.SupplierID
                WHERE ProductId = @0";
    var data = db.Query(sql, UrlData[0]);
    if(data.Count() == 0){
    Response.ContentType = "application/json";
    Json.Write(data, Response.Output);

A _PageStart.cshtml file is added to the JsonService folder, setting the layout page to null to prevent the JSON being polluted inadvertently with HTML. The second and third files perform some validation on UrlData to ensure that it is present and of the right data type before attempting to us the value to obtain data from the database. If there are any problems with the value, an HTTP status code of 400 is returned to the client, otherwise data is returned in JSON format using the JSON helper.

Good. That's all the plumbing sorted. The next thing to do is to create the view model, which represents all of the data that the UI will need. Just to recap the requirement, this will consist of the following:

  • A collection of categories
  • A collection of products
  • Details of a specific product

The view model is created using JavaScript, so it needs to go inside <script> tags. This will be injected into the RenderSection call in the layout page. So the first few lines of Default.cshtml look like this:

    Page.Title = "Knockout Sample";
@section script{
<script type="text/javascript">
    var viewModel;
    $(function() {
        viewModel = {
            productId: ko.observable(),
            productName: ko.observable(),
            contactTitle: ko.observable(),
            contactName: ko.observable(),
            companyName: ko.observable(),
            quantityPerUnit: ko.observable(),
            unitPrice: ko.observable(),
            unitsInStock: ko.observable(),
            categories: ko.observableArray([]),
            products: ko.observableArray([])

A variable for the view model is declared outside of the jQuery ready function that fires when all of the page has loaded. Within that function, the view model is defined. The first 8 properties relate to an individual product and are defined as ko.observable(). The parenthesis at the end of observable tell you that these are actually functions. They issue notifications to any observers when their values change. This is known as the Observer pattern. The two collections are defined as ko.observableArray(), which is the array equivalent of ko.observable. None of the view model's properties are initialised with a value. If you want to provide default values, you would supply them as arguments to the appropriate ko.observable method:

        viewModel = {
             productId: ko.observable(1),
             productName: ko.observable("Ham")

One of the application requirements is to provide a means for the user to buy a unit of their chosen product, and for the remaining number of units available to reflect the fact that one has gone. The viewModel object that has been declared needs a method to manage that: = function(){
            if(this.unitsInStock() > 0){
                this.unitsInStock(this.unitsInStock() - 1);
            } else {
               alert('Out of stock!');

As has been said before, observables are functions. When you want to access the value of one, you call the function with no arguments. If you want to set the value, you pass the new value into the function as an argument. The buy function first checks to see if the unitsInStock observable value is currently greater than zero. If it isn't an Out Of Stock message is displayed in an alert. Otherwise, the current value is decreased by one.

One more line of code is required to register the view model with Knockout:


The next block of code gets data in JSON format from the services that were created earlier:

        $.getJSON('/JsonService/GetCategories', function(data) {

        $('#categories').change(function() {
            $.getJSON('/JsonService/GetProductsByCategory/' + $(this).val(), function(data) {

        $('tr').live('hover', function() {
            $(this).css('cursor', 'pointer');
        }).live('click', function() {
            $.getJSON('/JsonService/GetProductById/' + $(this).find('td:first').text(), function(data) {
                var product = data[0];
                viewModel.unitPrice('£' + product.UnitPrice.toFixed(2));

The first getJSON call fetches the categories when the page loads. Then the viewModel.categories property is populated with the data. This will be bound to a dropdown list. The next getJSON call obtains products for a selected category. It fires when the dropdown list selection changes, and passes the list's selected value as a parameter. The resulting data populates the viewModel.products property. This is bound to a table for display. The final block of jQuery code makes each table row selectable and turns the mouse pointer to a hand. When a row is clicked on, the product's ID is obtained from the first cell in the row and used as a parameter in the getJSON call. The resulting data is bound manually to the individual properties in the viewModel object.

Finally, all this data needs to be displayed. I said earlier that Knockout offers a "declarative data binding" system. Now is the time to see what that actually means. Here's how the categories are bound to a dropdown list:

    <select id="categories" data-bind="options: viewModel.categories, 
                                       optionsText: 'CategoryName', 
                                       optionsValue: 'CategoryID', 
                                       optionsCaption: 'Choose...'"></select>

This has been broken over several lines for display on a web page, but it doesn't need to be. The key to the "declarative data binding" system is the HTML5 "data-bind" attribute. The "options" binding is used specifically for dropdown lists. The source data to be bound is specified, along with which part of the data should be bound to the text of an <option> element and which part should be bound to the "value" attribute. I have also used the optionsCaption to specify a default selection. Using this system, Knockout knows to bind the correct data to an HTML control, but it also knows that the bound data should change in response to changes in the underlying view model.

Once a category has been chosen, its associated products are retrieved and they need to be displayed somewhere. The next section of code shows how a <table> element is prepared for them:

        <tbody data-bind="foreach: viewModel.products"> 
                <td><span data-bind="text:ProductID"></span></td> 
                <td><span data-bind="text:ProductName"></span></td> 

This uses the "foreach" binding, which tells Knockout to duplicate a section of markup for each element in the observable array. Within the table cells, a span's text property is bound to the ProductID and the ProductName properties of each element in the array using the "text" binding.

Finally, once a product has been selected from this table, it's details need to be displayed:

<div id="details">
    <div class="row">
        <span class="label">Product:</span>
        <span data-bind="text: productName"></span>
    <div class="row">
        <span class="label">Supplier:</span>
        <span data-bind="text: companyName"></span>
    <div class="row">
        <span class="label">Contact:</span>
        <span data-bind="text: contactName"></span>
    <div class="row">
        <span class="label">Position:</span>
        <span data-bind="text: contactTitle"></span>
    <div class="row">
        <span class="label">Unit Price:</span>
        <span data-bind="text: unitPrice"></span>
    <div class="row">
        <span class="label">Quantity Per Unit:</span>
        <span data-bind="text: quantityPerUnit"></span>
    <div class="row">
        <span class="label">Units In Stock:</span>
        <span data-bind="text: unitsInStock"></span>
    <div class="row">
        <span class="label">&nbsp;</span>
        <span><button data-bind="click: buy">Buy One</button></span>

Each of the view model's properties are bound to spans using the text binding, but the final element - the button - is bound to the method using the "click" binding. When the button is clicked, the method is run and the amount displayed in Units In Stock is decremented by one as a result of the underlying change in the viewModel value.

You can test this for yourself by downloading the sample application from GitHub. It is written in Web Pages 2, but will run if you have not installed that version yet. Simply unzip the folder and right-click, then choose Open as a Web Site With WebMatrix.

There are other ways to achieve the same effect, but they often involve keeping track of events and targeting specific DOM elements with jQuery or similar to update values. Knockout takes care of that for you, as well as providing a really easy templating system and databinding syntax.


Date Posted:
Last Updated:
Posted by:
Total Views to date: 24333


- Shahnawaz Khan

Nice article on KnockOut JS.

The download link you've provided is not working and returning 404 error, please update the download link.


- Mike


I have updated the link for the sample app.

- 234


- Richard

Great working example!, which shows how to work with webmatrix and knockout.

- Alex

Hey Mike,

Awesome, as a complete beginner in web development I like your posts very much - as they are clear and do not omit simple but critical for understanding stuff.

I'm on Win 8 / IE 10, I've downloaded the code an ran it. Selection list shows nothing - any ideas why?

- Alex

Hi again,

After a while I broke through the wall - for some reason your html code for including javascripts did not work for me.

I had to change
<script src="~/Scripts/jquery-1.7.2.min.js"></script>
<script src="~/Scripts/knockout-2.1.0.js"></script>
<script src="/Scripts/jquery-1.7.2.min.js"></script>
<script src="/Scripts/knockout-2.1.0.js"></script>
to get it working... notice the missing '~'. For me '~' only works in Razor blocks @{}...


Recent Comments

satyabrata 19/06/2016 18:53
In response to Entity Framework Code First and Stored Procedures
Nice article. Thanks. The menu on this website not working in mobile....

satyabrata 16/05/2016 06:28
In response to Implementing SQL Server Full-Text Search In An ASP.NET MVC Web Application With Entity Framework
This is great. Thanks for sharing....

sharey 06/05/2016 13:15
In response to The Best Way To Import Data From Excel To SQL Server via ASP.NET
nice work gentleman.Really helpfull....

Satyabrata Mohapatra 20/04/2016 04:36
In response to The Best Way To Import Data From Excel To SQL Server via ASP.NET
Another beauty !!!! Thanks for sharing....

Avinash Setty 18/04/2016 18:39
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
This tool is awesome! I am very thankful for introducing this tool for us! By any chance, do you is...

flyingtigerfan 17/04/2016 22:56
In response to Request.Form Is Empty When Posting To ASPX Page
Thanks - spent hours trying to figure this out. I'm out of date and trying to start working on some...

Darren Evans 12/04/2016 16:42
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
'Tis indeed a marvellous thing. Just waiting on its appearance for ASP.NET Core. Hopefully not long...

Arkady 03/04/2016 12:09
In response to Request.Form Is Empty When Posting To ASPX Page
Thank you! I spent a day to understand what problem is before I found your article! But I made of...

satyabrata 03/04/2016 03:50
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
This is great!!!!!...

John Dave Bumatay 01/04/2016 02:01
In response to Windows Authentication With ASP.NET Web Pages
+1 ! This worked for me like a magic!~ thank you very much Mike! ;)...