Knockout.js is a javascript framework for creating MVVM like browser apps. MVVM stands for Model-View-ViewModel. Model represents the data. View represents the UI. ViewModel represents how the model is represented within the View. ViewModel also encapsulates the behaviour of the view. For eg, the rule: for some conditions in the data (model), set a green background to the table cell, is encapsulated within the ViewModel.

Knockout.js works on bindings. Every DOM element (View) is bound to JSON data (Model). Knockout.js provides a framework for creating ViewModels. In this post, we will create a simple ASP.NET MVC application which displays a DropDownList. The DropDownList is bound to JSON data coming from the controller. The example here is an adaptation of the example found in Knockout.js home page.

We will start with familiar territory – an ASP.NET MVC application with HomeController and Index View. The GetTickets() action method returns the model (List of tickets) as JSON data:

We have to pick up this data in our Knockout javascript. The code for creating the ViewModel out of the JSON data is shown below:

TicketsViewModel has two properties – tickets (List of tickets), and selectedTicket (Ticket selected in the dropdown). Both the properties are set to ko.observable(). ko is the knockout global variable, which is ubiquitiously used in Knockout.js (similar to $ in jQuery). ko.observable() ensures that any change in the value of tickets are reflected in the UI and vice-versa.

We then write the javascript for retrieving the model and setting it within the ViewModel. The jQuery AJAX calls the GetTickets() method in the HomeController and sets the JSON data to the ViewModel. Finally, ko.applyBindings() applies all the bindings set in the UI.

A point to note about Knockout.js is that: All Knockout.js code should be written after the HTML elements. Generally Knockout code should be placed at the end of the view.

Finally, the actual view (HTML elements) is shown below:

The select HTML tag is the Dropdownlist. The data-bind attribute provides the data binding expressions: options, optionsText, optionsCaption, value are all self-explanatory. The paragraph below the dropdownlist displays the selection made by the user. As you can see, Knockout.js provides custom attributes to DOM elements. The data-bind attribute is widely used. We should all familiarize with some of these attributes to do effective Knockout.js programming.

Finally, the script tags should be placed at the top of the page:

jQuery is not required for Knockout.js. But, as I have used jQuery (for making the AJAX call), I have included that as well. Knockout works well without jQuery. The only requirement from Knockout.js is that all the script should be placed at the bottom of the page, and not in the <head> tag as usually done.

Introduction to Knockout.js and ASP.NET MVC
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *