Which web apps use Knockout js

Single page application: knockoutjs template

  • 12 minutes to read

by Mike Wasson

The Knockout MVC template is part of ASP.NET and Web Tools 2012.2

Download ASP.net and Web Tools 2012.2

The ASP.NET and Web Tools 2012.2 update includes a single-page application (SPA) template for ASP.NET MVC 4. This template is designed to get you started creating interactive client-side web apps facilitate.

Single-Page Application (Spa) is the general term for a web application that loads a single HTML page and then dynamically updates the page instead of loading new pages. After the page loads initially, the spa will communicate with the server using AJAX requests.

AJAX is nothing new, but there are JavaScript frameworks out there today that make it easy to create and maintain a large sophisticated spa application. In addition, HTML 5 and CSS3 simplify the creation of comprehensive user interfaces.

To get you started, the spa template creates a sample task list application. In this tutorial, we're going to take a tour of the template. First we look at the application task lists ourselves and then examine the technological components that make them functional.

Create a new spa template project

Conditions:

  • Visual Studio 2012 or Visual Studio Express 2012 for web
  • ASP.NET Web Tools 2012.2 update. You can install the update here.

Start Visual Studio and select the option on the Start page New project out. Or choose in the menu file the option New and then Projectout.

Select in the area templates the option installed templates and expand the node visual C # Node. Choose under Visualization C # the option Webout. In the list of project templates, select the option ASP.NET MVC 4 web applicationout. Give the project a name and click OK.

In the wizard for new projects the option Single page applicationout.

Press F5 to build and run the application. The first time the application is run, a login screen will appear.

Click the "register" link and create a new user.

After you log in, the application creates a standard TODO list with two items. You can click the Add TODO List to add a new list.

Rename the list, add items to the list, and check it out. You can also delete items or delete an entire list. The changes are automatically saved persistently in a database on the server (actually localdb, since you run the application locally).

Spa template architecture

This diagram shows the main building blocks for the application.

On the server side, ASP.NET MVC processes the HTML code and also processes forms-based authentication.

ASP.NET Web API handles all requests related to the todolists and todoitems including creating, creating, updating and deleting. The client exchanges data with the web API in JSON format.

Entity Framework (EF) is the O / RM layer. It mediates between the object-oriented world of ASP.net and the underlying database. The database uses localbb, but you can change this in the web.config file. Typically, you would use localdb for local development and then deploy a SQL database on the server using EF Code First migration.

On the client side, the knockout is processed. js library pages updates to AJAX requests. Knockout uses data binding to keep the page in sync with the latest data. That way, you don't have to write code that iterates through the JSON data and updates the DOM. Instead, you add declarative attributes to the HTML that tells Knockout how to present the data.

A major advantage of this architecture is that the presentation level is separated from the application logic. You can create the web API part without knowing what you want your webpage to look like. On the client side, you create a "view model" to represent this data, and the view model uses knockout to bind to the HTML. So you can easily change the HTML code without changing the view model. (We'll look at Knockout later.)

Models

In the Visual Studio project, the "Models" folder contains the models that are used on the server side. (There are also models on the client side.

"Element", "Object List"

These are the database models for Entity Framework Code First. Note that these models have properties that point to each other. contains a collection of todoitems, and each has a reference to the parent ToDoList. These properties are known as navigation properties and represent the 1: n relationship of a task list and its to-do items.

The class also uses that [Foreign nkey] -Attribute to indicate that there is a foreign key in the table. This tells EF to add a FOREIGN KEY constraint to the database.

"-Doitemdto", "dolistdto"

These classes define the data that is sent to the client. "DTO" stands for "data transfer object". The DTO defines how the entities are serialized in JSON. In general, there are several reasons for using DTOs:

  • To control which properties are serialized. The DTO value can contain a subset of the properties from the domain model. This can be for security reasons (to hide sensitive data) or to reduce the amount of data you send.
  • To change the form of the data - ex. b. to simplify a more complex data structure.
  • To preserve business logic from the DTO (separation of concerns).
  • If for some reason your domain models cannot be serialized. Circular references can e.g. b. Cause problems when serializing an object. there are ways to handle this problem in the web API (see Processing Circular Object References); however, using a DTO simply avoids the problem.

In the spa template, the DTOs contain the same data as the domain models. However, they are still useful because they avoid circular references from the navigation properties and they illustrate the general DTO pattern.

AccountModels.cs

This file contains models for site membership. The class defines the schema for user profiles in the membership database. (In this case, the only information is the user ID and user name.) The other model classes in this file are used to create the user registration and login forms.

Entity Framework

The spa template uses EF Code First. In Code First Development, you first define the models in code, and EF uses the model to build the database. You can also use EF with an existing database (Database First).

The class in the Models folder is used by dbcontextderived. This class provides the "glue" between the models and EF. The contains a listing and a listing. To query the database, just write a LINQ query on these collections. For example, here is how you can select all to-do lists for user "Alice":

You can also add new items to the collection, update items, or delete items from the collection and keep the changes in the database.

ASP.NET Web API Controller

In the ASP.NET Web API, controllers are objects that process HTTP requests. As mentioned earlier, the spa template uses the web API to enable CRUD operations on and on instances. The controllers are located in the "Controllers" folder in the project folder.

  • : handles HTTP requests for to-do items.
  • : handles HTTP requests for task lists.

These names are important because the web API corresponds to the URI path with the controller name. (For information about how the Web API routes HTTP requests to controllers, see Routing in ASP.NET Web API.)

Let's look at the class. It contains a single data member:

The is used for communication with EF as described above. The methods on the controller implement the CRUD operations. The web API maps HTTP requests from the client to the controller methods as follows:

HTTP requestController methoddescription
GET / api / todoGets a collection of to-do lists.
/ API / TODO / -ID receiveRetrieves a task list by ID.
/ API / TODO / -ID placeUpdates a task list.
POST / api / todoCreates a new task list.
/ API / TODO / -ID ClearClears a TODO list.

Note that the URIs for some operations contain placeholders for the ID value. If you z. b. want to delete a list with ID 42, the URI.

For more information about using the web API for CRUD operations, see Creating a Web API That Supports CRUD Operations. The code for this controller is pretty straightforward. Here are some interesting points:

  • The method uses a LINQ query to filter the results by the ID of the logged in user. In this way, only the data that belongs to them is shown to a user. Also note that a SELECT statement is used to convert the instances to instances.
  • The put and post methods check the model status before modifying the database. If " modelstate. IsValid If "is false", these methods return an invalid request HTTP 400. For more information about model validation in the Web API, see Model Validation.
  • The controller class is also used with the [authorized] -Attribute provided. This attribute checks that the HTTP request is authenticated. If the request is not authenticated, the client receives HTTP 401, unauthorized. For more information about authentication, see Authentication and Authorization in ASP.NET Web API.

The class is similar. The biggest difference is that no get methods are defined because the client receives the to-do items with each task list.

MVC controllers and views

The MVC controllers are also located in the "Controllers" folder in the project folder. renders the main HTML for the application. The view for the home controller is in views / Home / Index. cshtml. The start view renders different content depending on whether the user is logged in:

When users are logged in, the main user interface is displayed. Otherwise the login panel is displayed. Note that this conditional rendering is done on the server side. Never try to hide sensitive content on the client side — what you send in an HTTP response will be visible to someone watching the raw HTTP messages.

Client-side JavaScript and knockout. js

Now we switch the server side of the application to the client. The spa template uses a combination of jQuery and Knockout. js to create a smooth, interactive user interface. Knockout. js is a JavaScript library that makes it easy to bind HTML to data. Knockout. js uses a pattern called "Model-View-ViewModel".

  • The model is the domain data (TODO lists and TODO elements).
  • The view is the HTML document.
  • The view model is a JavaScript object that contains the model data. The view model is a code abstraction of the user interface. The HTML representation is unknown. Instead, it represents abstract functions of the view, e.g. b. "a list of TODO items".

The view is data bound to the view model. Updates to the view model are automatically reflected in the view. Bindings work the other way too. Events in the dome (e.g. clicks) are data tied to functions in the view model that trigger AJAX calls.

The spa template organizes the client-side JavaScript in three levels:

  • TO DO. DataContext. js: sends AJAX requests.
  • TO DO. Model. js: defines the models.
  • TO DO. ViewModel. js: defines the view model.

These script files are located in the "Scripts / app" folder in the solution.

TO DO. DataContext processes all AJAX calls to the web API controllers. (The AJAX calls for login are defined elsewhere in "ajaxLogin. Js".)

TO DO. Model. js defines the client-side (browser) models for the task lists. There are two classes of models: "tdoitem" and "tdolist".

Many of the properties in the model classes are of the "ko. Observable" type. Observables is how Knockout does its magic. From the Knockout documentation: an observable object is a JavaScript object that can notify subscribers of changes. When the value of an observable element changes, Knockout updates all HTML elements that are bound to those observables. For example, "" for "" has the property "Title" and "isdone" has the property "Title":

You can also subscribe to an observable element in code. For example, the "dedoitem" class subscribes to changes in the "isdone" and "Title" properties:

Show model

The view model is in TODO. ViewModel. js defined. The view model is the central point at which the application binds the HTML page elements to the domain data. In the spa template, the view model contains an observable array of "task lists". The following code in the view model instructs Knockout to apply the bindings:

HTML and data binding

The main HTML for the page is in views / home / index. cshtml. Because data binding is used, the HTML is just a template for what is actually being rendered. Knockout used declarative Ties. You bind page elements to data by adding a "Data-BIND" attribute to the element. Here is a very simple example taken from the Knockout documentation:

In this example, Knockout updates the contents of the <spannen> Elements with the value. If this value changes, Knockout updates the document.

Knockout provides a number of different types of bindings. The following are some of the bindings used in the spa template:

  • foreach: Lets you go into a loop and apply the same markup to each item in the list. This is used to render the task lists and task items. Within foreachthe bindings are applied to the elements of the list.
  • Visible: is used to switch the visibility. Hide markup when a collection is empty or make the error message visible.
  • value: is used to populate form values.
  • Click: binds a click event to a function in the view model.

Anti-CSRF protection

Cross-Site Request Forgery (CSRF) is an attack in which a malicious site sends a request to a vulnerable site where the user is currently logged in. To prevent CSRF attacks, ASP.NET uses MVC anti-counterfeit token, also known as a request verification token. The idea is for the server to insert a randomly generated token into a webpage. When the client submits data to the server, it must include this value in the request message.

Anti-forgery tokens work because the malicious side cannot read the user's tokens due to policies for the same origin. (The same origin guidelines prevent documents hosted in two different locations from accessing each other's content.)

ASP.NET MVC has built-in support for anti-forgery tokens through the anti-forgery class and the [validateantiforgerytoken] attribute. This function is not currently integrated into the web API. However, the spa template includes a custom implementation for the web API. This code is defined in the class, which is located in the "Filters" folder of the solution. For more information about anti-CSRF in the web API, see Preventing Cross-Site Request Forgery (CSRF) attacks.

Summary

The spa template is designed so that you can quickly start writing modern, interactive web applications. It uses the knockout. js library to separate the representation (HTML markup) from the data and application logic. However, Knockout isn't the only JavaScript library you can use to create a spa. If you'd like to explore other options, check out the community-created spa templates.