Knockout.js Role In ASP.NET MVC Application | Knockout.js Tutorial | ASP.NET MVC Tutorial | ASP.NET Web API Tutorial

, ,
Knockout.js is a Javascript library that makes it easy to bind HTML controls to data. Knockout.js uses the Model-View-ViewModel (MVVM) pattern.
  • The model is the server-side representation of the data in the business domain (in our case, products and orders).
  • The view is the presentation layer (HTML).
  • The view-model is a Javascript object that holds the model data. The view-model is a code abstraction of the UI. It has no knowledge of the HTML representation. Instead, it represents abstract features of the view, such as "a list of items".
The view is data-bound to the view-model. Updates to the view-model are automatically reflected in the view. The view-model also gets events from the view, such as button clicks, and performs operations on the model, such as creating an order.

Cascading Dropdown using Knockoutjs and ASP.NET MVC | ASP.NET MVC Tutorial | Knockoutjs Tutorial

This guide will walk you through building cascading drop down using knockoutjs and ASP.NET MVC. We leverage knockoutjs to create UI which update itself based on user interaction. Sample can be downloaded from here.
Below view is presented with drop down list loaded with countries and upon selecting any country user is presented with another drop down which lists states for the selected country. This sample uses jQuery.getJSON to fetch list of states for selected country. Server will return state list in JSON format.

Magic of knockoutjs

We have created a ASP.NET MVC view and model with MVVM pattern used by knockoutjs. Whenever the data source refresh at that time we only need to update underlying viewModel and the rest will be taken care by knockoutjs including updating UI based on refreshed data.
Code snippet for Home controller & State model class:
public class HomeController : Controller
    public ActionResult Index()
        ViewBag.Country = new SelectList(Country.GetCountryList(), "Code", "Name");
        return View();
    public ActionResult GetStates(string id = "")
        var stateList = State.GetStates()
            .Where(s => s.CountryCode.ToLower() == id.ToLower());
        return this.Json(stateList, JsonRequestBehavior.AllowGet);
// State model class
// Property of State class is used to 
// bind view with knockoutjs viewmodel
public class State
    public string CountryCode { get; set; }
    public int StateId { get; set; }
    public string StateName { get; set; }
Code snippet for index.cshtml:
<b>Select Country :</b> @Html.DropDownList("ddlCountry", ViewBag.Country as SelectList, "Select...", new { onchange = "FetchStates();" })
<p data-bind="visible: states().length > 0">
<b>Select State :</b> <select data-bind="options: states, optionsText: 'StateName', optionsValue: 'StateId', optionsCaption: 'Choose...'"></select>
Code snippet for ViewModel defined in JavaScript:
function CascadingDDLViewModel() {
    this.states = ko.observableArray([]);
var objVM = new CascadingDDLViewModel();
We are creating a view model with states property of type ko.observableArray. Observable type in knockoutjs will notify automatically whenever underlying object is updated.
In index.cshtml snippet, we are using this states property with data-bind attribute that binds DOM element behavior with knockoutjs ViewModel. So DOM elements will be updated automatically whenever ViewModel changes. 
Following JavaScript function will be called whenever user selects a country. With the help of jQuery.getJSON method, we fetch list of states and assigning the states to the states property of the viewmodel. As the viewmodel changes. knockoutjs will take care of loading a dropdown for states.
function FetchStates() {
    var countryCode = $("#ddlCountry").val();
    $.getJSON("/Home/GetStates/" + countryCode, null, function (data) {
Sample code can be downloaded here.

Developing A Website Using ASP.NET MVC 4, EF, Knockoutjs And Bootstrap

, ,
All websites are growing faster these days, and once it grows, it is very hard to write, organize and maintain. As we add new functionality or developer to a project, any large web applications with poor design may be go out of control. So the idea behind this article is to design a website architecture that must be simple, easily understandable by any web designer (beginner to intermediate) and Search Engines. For this article I am trying to design a website for any individuals to maintain their contact details online. However, in future, the same application could be used by large community all over the world with added functionality and modules. So, the design should be easily adaptable in order to cope with the future growth of business.

In this article we will talk about creating and designing User Interface (UI) in such a manner so that UI will be separated from the business logic, and can be created independently by any designer/developer. For this part we will use ASP.Net MVC, Knockout Jquery and Bootstrap. later in this article we will discuss more about database design and implementing business logic using structured layers using SQl Server 2008, Entity Framework, and Castle Windsor for Dependency Injection.

Best Place To Refer Knockout.js File | Knockoutjs


In general, it is better to reference the scripts at the bottom of the page. Mainly, it allows the page to appear to render faster to the end user because the entire visual markup is processed before the script references are, and thus will be displayed on the web browser's screen while the referenced JavaScript files are downloading and being processed into the browser's memory.

Knockout is a library that works with the browser's Document Object Model (DOM), and in order to do so, the browser needs to have created and rendered the content portions of the DOM before Knockout executes. So, simply as a best practice we place our JavaScript files at the bottom of the page in order to give our users the best experience possible.

Knockoutjs Video Tutorial | Knockout.js Video Demo Series


Knockout.js Lesson 14 - Adding a Lightbox | Knockoutjs Video Tutorial


In the last practical lesson of the course, we add a final feature to our application - a simple lightbox. This is a basic demo to show how easy it is to add these kinds of new features when using Knockout, and a bit of practice using some more bindings and working with viewModel properties.

Knockout.js Lesson 13 - Additional Knockout Features | Knockoutjs Video Tutorial


In lesson 13, we take a quick look at some useful features of Knockout which we don't need to use in our application, but which are nevertheless worth a mention. We look at virtual elements, the mapping plugin and a range of other bindings that we can make use of when developing with Knockout.

Knockout.js Lesson 12 - The Value Binding | Knockoutjs Video Tutorial


In lesson 12, we will see how we can use the value binding on an input element in order to add filtering capabilities to our demo application. We add the ability to filter by title, and then return to the complete collection of images when the filter is removed.

Knockout.js Lesson 11 - The Visible Binding | Knockoutjs Video Tutorial


In today's lesson, we take a look at the visible binding in order to add a button to our UI that is only displayed once an editable element has actually been edited. We also look at Knockout's toJS and toJSON methods in order to serialize our viewModel and convert it to a JSON string perfect for sending to a server or other storage medium.

Knockout.js Lesson 10 - Computed Observables | Knockoutjs Video Tutorial


In lesson 10, we look at a feature of Knockout called computed observables. These are special functions that reference one or more viewModel properties (either observables or observable arrays), and which are invoked whenever the value of the property or properties changes. This is an extremely useful feature for creating dependency chains between properties of the viewModel.

Knockout.js Lesson 9 - Custom Bindings | Knockoutjs Video Tutorial


In lesson 9, we create our own custom binding in order to allow contentEditable elements that are edited to have their new text values automatically saved back to the viewModel, replacing the built-in text binding provided by Knockout.

Knockout.js Lesson 8 - The Click Binding | Knockoutjs Video Tutorial


We start lesson 8 with a little refactoring to tidy up our initialization method, and add a light skin to smarten up the application's appearance. We then move on to make the photo titles editable using Knockout's click binding - a specialised version of the event binding for working purely with click events.

Knockout.js Lesson 7 - The event binding | Knockoutjs Video Tutorial


In today's lesson, we look at the event binding, and use it to wire up the sorts that we started looking at in lesson 6. We see how to connect the change event of the select box to a method of our viewModel so that we can invoke the correct sorter function and change the order of the images on the page.

Get the code for this series from Github

Knockout.js Lesson 6 - The foreach binding | Knockoutjs Video Tutorial


Control bindings - foreach

In lesson 6, we take a look at one of Knockout's control bindings - the foreach binding, which allows us to repeat a block of mark-up for each item in an observed array. This is Knockout's built-in form of templating. We also make use of an observable array to add a sort feature to the application.

Get the code for this series from Github

Knockout.js Lesson 5 - Observable arrays | Knockoutjs Video Tutorial


Today we're going to look at observable arrays in Knockout.js. Observable arrays are similar to observables, except that instead of subscribing to a single property and reacting when it's value changes, we can subscribe to an array and be notified whenever the array changes, either through having items added or removed, or through an operation like sorting or filtering. We use an observable array to store the photos that we receive from Flickr, and also work with jQuery's promise API.

Knockout.js Lesson 4 - Basic bindings | Knockoutjs Video Tutorial


In lesson 4, we look at some of the basic bindings that Kncokout provides and which allow us to seamlessly connect our user interface to our viewModel. We discuss the form bindings, control bindings and template binding, and also look at what the binding context is. We then implement the text binding in order to display some of the data we get from Flickr, and the if binding to only show these elements once they have been populated.

Knockout.js Lesson 3 - Adding a viewModel | Knockoutjs Video Tutorial


In this lesson, we put together a basic viewModel and see how to populate it with Knockout observable properties. These are special properties that Knockout will monitor for us and notify other parts of the application when their values change.

Knockout.js Lesson 2 - Initialising the application | Knockoutjs Video Tutorial


In lesson 2, we add the wrapper for our app and see how easy it is to create a simple constructor for our application that accepts configuration options and supports chaining. We also saw how to use jQuery's extend method to merge the configuration object with the default properties of the application.

Knockout.js Lesson 1 - Introduction | Knockoutjs Tutorial


In this series you will learn to build a simple photo app with Knockout.js. Knockout.js is a simple and powerful client side javascript framework used to create complex user interfaces.In the course introduction, we look at what Knockout.js is, what architectural pattern it is built on, and how it can help us rapidly develop sophisticated, interactive user interfaces that don't turn into a tangled mess of event handlers. We also set up our development area ready to start coding in lesson 2

Binding Knockoutjs View Model Using DOM Element ID | Knockout.js

There are scenarios where we have two view models in a single view. In such case, the binding can be done using the ko.applyBindings, adding the DOM element id as the second parameter. To achieve this, we need to wrap the forms (or set of controls) in separate DOM element like<div>. The, set unique element id for each <div> enclosing the controls. 
Use the id as the second parameter for ko.applyBindings and bind the view models separately. Below  sample code has bookTitle and btnSubmit in both the forms; the separate view models is bound using DOM-Element id that aggregates both the control sets.