Thursday, January 31, 2013

Knockout Web API SPA

This is just to explore the new technologies in the Microsoft .Net and Javascript communities. The Web API allows for a lightweight web services tier, while Knockout provides productivity in the browser side. Most of this technique I found in tutorials on www.asp.net and other like sites. I am not feigning originality here.
I am describing the building of a SPA - Single Page Application.
I have built a quick application which performs CRUD operations on the single table using Knockout, Web API, and NHibernate data layer.
Here is the browse data view of the application. There are links to edit, delete and add new items. Also it does paging, because the table is large.

Here is the Edit data view :


How is it built?

A standard MVC project is created in C#, selecting the WEB API project template along the way. A Project Reference is added to the data layer project.


There are 3 main components needed to get a UI running : a Controller class, a Javascript file, and an HTML View file.


The HTML View


References to the various script libraries are added

It is easiest is to build the View and then animate it with code. The View I have above contains edit and list sections which are hidden and shown alternatively, using the JQuery “Hide” and “Show” commands. Just to explain the syntax, here is the relevant part of the Edit section :
And the pertinent code for the List section :
The edit and delete links are accomplished with Knockout Bindings as shown here:

The data paging functionality is also done with Knockout bindings :
The Scripting
Knockout implements the ViewModel part of the MVVM architecture which means we have to code this in the javascript for the html page. Here is my example ViewModel which works in the single page application :
This ViewModel contains objects for the single item and the list of those items.
The Controller code
This is a class which implements the API methods to return data for Knockout to display. The WEB API uses convention to determine which method to execute. Objects are posted intact to the methods, and parameters passed with names are converted to querystring. If passed without name to a GET function, then the value just becomes part of the path "API/THING/1/" for example. Posts and Deletes are translated into methods with those names.

1 comment:

Unknown said...

Seriously...thank you. One of the only samples of ko.mapping that makes any sense...bless you : )