Knockout.js is a client-side Javascript framework for creating single page applications. Central to the framework is the VIewModel
. ViewModel
represents the model or data for the View. It also has the behavior of the view. Click event handlers are part of the ViewModel
.
DOM elements (View) are bound to ViewModel
. We create a simple ASP.NET MVC application which displays a DropDown
. The DropDown
is bound to JSON data coming from the controller.
Controller
We will start with the ASP.NET MVC application. The GetTickets
action returns the model (List of tickets) as JSON data.
public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult GetTickets() { Ticket[] tickets = new Ticket[] { new Ticket { Name = "Economy", Price = "$99" }, new Ticket { Name = "Business", Price = "$199" }, new Ticket { Name = "First Class", Price = "$399" } }; return this.Json(tickets, JsonRequestBehavior.AllowGet); } }
ViewModel
We create the TicketsViewModel
. Call the controller to get a list of tickets as JSON. Pass the data to the ViewModel
. In Knockout, all properties are observables. When the data within the observable changes, the view gets updated with the new data.
<script type="text/javascript"> function TicketsViewModel() { this.tickets = ko.observable(); this.selectedTicket = ko.observable(); } $(document).ready( function () { var ticketsViewModel = new TicketsViewModel(); $.get("/Home/GetTickets", function (data) { ticketsViewModel.tickets(data); }); ko.applyBindings(ticketsViewModel); }); </script>
TicketsViewModel
has two observable properties, tickets and selectedTicket. ko
is a global variable (similar to $ in jQuery).
All Knockout code should be placed at the end of the body tag.
data-bind attribute
Decorate the HTML with data-bind
attributes. These data-bind
expressions are unique to Knockout. Please refer to the documentation on how to use them.
<div> <select data-bind="options: tickets, optionsText: 'Name', optionsCaption: 'Select...', value: selectedTicket"> </select> <p data-bind="with: selectedTicket">You selected <span data-bind="text: Name"></span>, price <span data-bind="text: Price"></span></p> </div>
Finally, place jQuery and Knockout within the head tag.
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.7.1.js")"></script> <script type="text/javascript" src="@Url.Content("~/Scripts/knockout-2.1.0.js")"></script>
jQuery is not required for Knockout.js. We used jQuery for making an API call.