Part 5: Creating a Dynamic UI with Knockout.js
by Mike Wasson
Creating a Dynamic UI with Knockout.js
In this section, we’ll use Knockout.js to add functionality to the Admin view.
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.
First we’ll define the view-model. After that, we will bind the HTML markup to the view-model.
Add the following Razor section to Admin.cshtml:
[!code-cshtmlMain]
1: @section Scripts {
2: @Scripts.Render("~/bundles/jqueryval")
3: <script type="text/javascript" src="@Url.Content("~/Scripts/knockout-2.1.0.js")"></script>
4: <script type="text/javascript">
5: // View-model will go here
6: </script>
7: }
You can add this section anywhere in the file. When the view is rendered, the section appears at the bottom of the HTML page, right before the closing </body> tag.
All of the script for this page will go inside the script tag indicated by the comment:
[!code-htmlMain]
1: <script type="text/javascript">
2: // View-model will go here
3: </script>
First, define a view-model class:
[!code-javascriptMain]
1: function ProductsViewModel() {
2: var self = this;
3: self.products = ko.observableArray();
4: }
ko.observableArray is a special kind of object in Knockout, called an observable. From the Knockout.js documentation: An observable is a “JavaScript object that can notify subscribers about changes.” When the contents of an observable change, the view is automatically updated to match.
To populate the products
array, make an AJAX request to the web API. Recall that we stored the base URI for the API in the view bag (see Part 4 of the tutorial).
[!code-javascriptMain]
1: function ProductsViewModel() {
2: var self = this;
3: self.products = ko.observableArray();
4:
5: // New code
6: var baseUri = '@ViewBag.ApiUrl';
7: $.getJSON(baseUri, self.products);
8: }
Next, add functions to the view-model to create, update, and delete products. These functions submit AJAX calls to the web API and use the results to update the view-model.
[!code-javascriptMain]
1: function ProductsViewModel() {
2: var self = this;
3: self.products = ko.observableArray();
4:
5: var baseUri = '@ViewBag.ApiUrl';
6:
7: // New code
8: self.create = function (formElement) {
9: // If the form data is valid, post the serialized form data to the web API.
10: $(formElement).validate();
11: if ($(formElement).valid()) {
12: $.post(baseUri, $(formElement).serialize(), null, "json")
13: .done(function (o) {
14: // Add the new product to the view-model.
15: self.products.push(o);
16: });
17: }
18: }
19:
20: self.update = function (product) {
21: $.ajax({ type: "PUT", url: baseUri + '/' + product.Id, data: product });
22: }
23:
24: self.remove = function (product) {
25: // First remove from the server, then from the view-model.
26: $.ajax({ type: "DELETE", url: baseUri + '/' + product.Id })
27: .done(function () { self.products.remove(product); });
28: }
29:
30: $.getJSON(baseUri, self.products);
31: }
Now the most important part: When the DOM is fulled loaded, call the ko.applyBindings function and pass in a new instance of the ProductsViewModel
:
[!code-javascriptMain]
1: $(document).ready(function () {
2: ko.applyBindings(new ProductsViewModel());
3: })
The ko.applyBindings method activates Knockout and wires up the view-model to the view.
Now that we have a view-model, we can create the bindings. In Knockout.js, you do this by adding data-bind
attributes to HTML elements. For example, to bind an HTML list to an array, use the foreach
binding:
[!code-htmlMain]
1: <ul id="update-products" data-bind="foreach: products">
The foreach
binding iterates through the array and creates child elements for each object in the array. Bindings on the child elements can refer to properties on the array objects.
Add the following bindings to the “update-products” list:
[!code-htmlMain]
1: <ul id="update-products" data-bind="foreach: products">
2: <li>
3: <div>
4: <div class="item">Product ID</div> <span data-bind="text: $data.Id"></span>
5: </div>
6: <div>
7: <div class="item">Name</div>
8: <input type="text" data-bind="value: $data.Name"/>
9: </div>
10: <div>
11: <div class="item">Price ($)</div>
12: <input type="text" data-bind="value: $data.Price"/>
13: </div>
14: <div>
15: <div class="item">Actual Cost ($)</div>
16: <input type="text" data-bind="value: $data.ActualCost"/>
17: </div>
18: <div>
19: <input type="button" value="Update" data-bind="click: $root.update"/>
20: <input type="button" value="Delete Item" data-bind="click: $root.remove"/>
21: </div>
22: </li>
23: </ul>
The <li>
element occurs within the scope of the foreach binding. That means Knockout will render the element once for each product in the products
array. All of the bindings within the <li>
element refer to that product instance. For example, $data.Name
refers to the Name
property on the product.
To set the values of the text inputs, use the value
binding. The buttons are bound to functions on the model-view, using the click
binding. The product instance is passed as a parameter to each function. For more information, the Knockout.js documentation has good descriptions of the various bindings.
Next, add a binding for the submit event on the Add Product form:
[!code-htmlMain]
1: <form id="addProduct" data-bind="submit: create">
This binding calls the create
function on the view-model to create a new product.
Here is the complete code for the Admin view:
[!code-cshtmlMain]
1: @model ProductStore.Models.Product
2:
3: @{
4: ViewBag.Title = "Admin";
5: }
6:
7: @section Scripts {
8: @Scripts.Render("~/bundles/jqueryval")
9: <script type="text/javascript" src="@Url.Content("~/Scripts/knockout-2.0.0.js")"></script>
10: <script type="text/javascript">
11: function ProductsViewModel() {
12: var self = this;
13: self.products = ko.observableArray();
14:
15: var baseUri = '@ViewBag.ApiUrl';
16:
17: self.create = function (formElement) {
18: // If valid, post the serialized form data to the web api
19: $(formElement).validate();
20: if ($(formElement).valid()) {
21: $.post(baseUri, $(formElement).serialize(), null, "json")
22: .done(function (o) { self.products.push(o); });
23: }
24: }
25:
26: self.update = function (product) {
27: $.ajax({ type: "PUT", url: baseUri + '/' + product.Id, data: product });
28: }
29:
30: self.remove = function (product) {
31: // First remove from the server, then from the UI
32: $.ajax({ type: "DELETE", url: baseUri + '/' + product.Id })
33: .done(function () { self.products.remove(product); });
34: }
35:
36: $.getJSON(baseUri, self.products);
37: }
38:
39: $(document).ready(function () {
40: ko.applyBindings(new ProductsViewModel());
41: })
42: </script>
43: }
44:
45: <h2>Admin</h2>
46: <div class="content">
47: <div class="float-left">
48: <ul id="update-products" data-bind="foreach: products">
49: <li>
50: <div>
51: <div class="item">Product ID</div> <span data-bind="text: $data.Id"></span>
52: </div>
53: <div>
54: <div class="item">Name</div>
55: <input type="text" data-bind="value: $data.Name"/>
56: </div>
57: <div>
58: <div class="item">Price ($)</div>
59: <input type="text" data-bind="value: $data.Price"/>
60: </div>
61: <div>
62: <div class="item">Actual Cost ($)</div>
63: <input type="text" data-bind="value: $data.ActualCost"/>
64: </div>
65: <div>
66: <input type="button" value="Update" data-bind="click: $root.update"/>
67: <input type="button" value="Delete Item" data-bind="click: $root.remove"/>
68: </div>
69: </li>
70: </ul>
71: </div>
72:
73: <div class="float-right">
74: <h2>Add New Product</h2>
75: <form id="addProduct" data-bind="submit: create">
76: @Html.ValidationSummary(true)
77: <fieldset>
78: <legend>Contact</legend>
79: @Html.EditorForModel()
80: <p>
81: <input type="submit" value="Save" />
82: </p>
83: </fieldset>
84: </form>
85: </div>
86: </div>
Run the application, log in with the Administrator account, and click the “Admin” link. You should see the list of products, and be able to create, update, or delete products.
|