Note: This article is part of the ASP. NET Web API Series tutorial, if you are looking at this blog post for the first time, please look at the previous content first.
Part 5:creating a Dynamic UI with Knockout.js
Part 5th: Creating a dynamic UI with Knockout.js
This article quoted: http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/ Using-web-api-with-entity-framework,-part-5
Creating a Dynamic UI with Knockout.js
Creating a dynamic UI with Knockout.js
In this section, we'll use knockout.js to add functionality to the Admin view.
In this section, we will add functionality to the admin view with Knockout.js.
Knockout.js is a Javascript library this makes it easy-to-bind HTML controls to data. Knockout.js uses the Model-view-viewmodel (MVVM) pattern.
Knockout.js is a JavaScript library that makes it easy for HTML controls to bind to data. Knockout.js is using model-view-view model (MVVM) mode.
- The model is the server-side representation of the "The Business Domain" (in our case, products and orders) .
A model is a server-side representation of data in a transactional domain (in our case, products and orders).
- The view is the presentation layer (HTML).
A view is a 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".
A view model is a JavaScript object that holds model data. A view model is a code abstraction for the UI. It has no knowledge of the HTML representation, but it represents the abstract nature of the view, such as list items.
The view is data-bound to the View-model. Updates to the View-model is 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 Creati ng an order.
Views are bound to the view model data. Updates to the view model are automatically reflected in the views. The view model also gets the view's events, such as button clicks, and performs actions on the model (see Figure 2-23).
Figure 2-23. The relationship between model-view-View models
First we ' ll define the View-model. After that, we'll bind the HTML markup to the View-model.
First, we want to define the view model. After that, you bind the HTML markup to the view model.
ADD the following Razor section to admin.cshtml:
Add the following razor fragment to admin.cshtml:
@section Scripts { @Scripts. Render ("~/bundles/jqueryval") <script type= "Text/javascript" src= "@ Url.content ("~/scripts/knockout-2.1.0.js") "></script> <script type=" Text/javascript "> // View-model 'll go here//view model will be put here </script>}
You can add this section anywhere in the file. When the view was rendered, the section appears at the bottom of the HTML page, right before the closing </body> tag.
You can add this fragment to any location in the file. When the view is rendered, the fragment appears at the bottom of the HTML page,</body> the front of the close tag.
All of the script to this page would go inside the script tag indicated by the comment:
All scripts used for this page are placed in the script tag indicated by the following note:
<script type= "Text/javascript" > //View-model'll go here// view model will be put here </script>
First, define a View-model class:
First, define a view model class:
function Productsviewmodel () { var = this; Self.products = Ko.observablearray (); }
Ko.observablearray is a special kind of the object in the Knockout, called an observable. From the Knockout.js Documentation:an observable are a "JavaScript object that can notify subscribers about changes." When the contents of a observable change, the view was automatically updated to match.
Ko.observablearray is a special object in knockout called observable (please call this observable object a visible object .) This object is often used as a view model to interact with the view, which is transparent and visible, so it is called a visible object. In the following translations, this observable object is called a visible object-the translator's note. According to the description of the Knockout.js document: A visible object is a "JavaScript object that notifies the subscriber of changes in data." When the contents of a visible object change, the view automatically matches the update.
To populate the "products" array, make a 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).
To populate the products array, you need to form a request to send to the Web API. Recall the base URI that we stored in the view bag for this API (see part 4th of this tutorial).
function Productsviewmodel () { var = this;
New Code // var BaseUri = ' @ViewBag. Apiurl '; $.getjson (BaseUri, self.products); }
Next, add functions to the View-model to create, update, and delete products. These functions submit AJAX calls to the Web API with use of the results to update the View-model.
Next, the view model adds functions to create, update, and delete products. These functions submit Ajax calls to the Web API and use the resulting results to update the view model.
function Productsviewmodel () {var = this; Self.products = Ko.observablearray ();
var BaseUri = ' @ViewBag. Apiurl ';
New Code//self.create = function (formelement) {//If the form data is valid, post the serialized form data to the Web API. If the form data is valid, submit the serialized form data to the Web API $ (formelement). Validate (); if ($ (formelement). Valid ()) {$.post (BaseUri, $ (formelement). Serialize (), NULL, "JSON"). Done ( Function (o) {//ADD the new product to the View-model. Add a new product to the view model Self.products.push (o); }); } }
Self.update = function (product) {$.ajax ({type: "PUT", Url:baseuri + '/' + product. Id, data:product}); }
Self.remove = function (product) {//First remove from the server and then from the View-model. First remove from the server and then remove $.ajax from the view model ({type: "delete", Url:baseuri + '/' + product. Id}). Done (function () {self.products.remove (product);}); }
$.getjson (BaseUri, self.products); }
Now the most important part:when the DOM was fulled loaded, call the ko.applybindings function and pass in a new Instance of the Productsviewmodel:
Now, the most important part: When the DOM is all loaded, call the ko.applybindings function and pass a new Productsviewmodel instance in it:
$ (document). Ready (function () { ko.applybindings (new Productsviewmodel ());})
The ko.applybindings method activates Knockout and wires up the view-model to the view.
The ko.applybindings method activates knockout and joins the view model with the view.
Now, we have a view-model, we can create the bindings. In Knockout.js, the adding data-bind attributes to HTML elements. For example, to bind a HTML list to a array, use the foreach binding:
Now that we have a view model, we can create bindings (the binding meaning here is to bind the data items in the view model to the individual HTML controls in the view-the translator's note). In Knockout.js, by putting the data-bind tag attribute (the tag attribute is the attribute of the HTML element, the purpose of the translation is also different from the property of the class-the translator notes) the way to add to the HTML element to do this. For example, to bind an HTML list to one data, use a foreach binding:
<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 elements can refer to properties on the array objects.
The foreach binding iterates through the array and creates child elements for each object in the group. A binding on a child element can point to a property on an array object.
Add the following bindings to the "update-products" list:
adds the following bindings to the Update-products list:
<ul id= "update-products" data-bind= "foreach:products" > <li> <div> <div class = "Item" >product id</div> <span data-bind= "text: $data. Id "></span> </div> <div> <div class=" Item ">Name</div> <input type= "text" data-bind= "value: $data. Name "/> </div> <div> <div class=" Item ">price ($) </div> <!--here The $ representation of dollar character-translator-<input type= "text" data-bind= "value: $data. Price "/> </div> <div> <div class=" item ">actual Cost ($) </div> <input type= "text" data-bind= "value: $data. ActualCost "/> </div> <div> <input type=" button "value=" Update "data-bind=" cl Ick: $root. Update "/> <input type=" button "value=" Delete Item "data-bind=" click: $root. Remove "/> </div> </li> </ul>
The <LI> element occurs within the scope of the foreach Binding. That means Knockout would render the element once for each product in the products Arra Y. 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.
<LI> element appears within the scope of the foreach binding. This means that knockout renders an element for each product in the products array. In <LI> all bindings in the element point to this product instance. For example, $data. The Name refers to the name property on the product.
To set the values of the text inputs, use the value binding. The buttons is 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 have good descriptions of the various bindings.
Sets the value of the text input box to use the value binding. button to bind to a function on the view model, you use the click Binding. The product instances are passed as parameters to each function. For more information, the Knockout.js document has a good description of the various bindings.
Next, add a binding for the submit event on the Add Product form:
Next, add a binding for the submit(Submit) event on the Add product form:
<form id= "addproduct" data-bind= "Submit:create" >
This binding calls the create function on the View-model to create a new product.
This binding invokes the CREATE function on The view model to create a new product.
Here are the complete code for the Admin view:
The following is the full code for the admin view:
@model ProductStore.Models.Product
@{viewbag.title = "Admin";}
@section Scripts {@Scripts. Render ("~/bundles/jqueryval") <script type= "Text/javascript" src= "@Url. Content (" ~/ Scripts/knockout-2.0.0.js ")" ></script> <script type= "Text/javascript" > Function Productsviewmodel ( {var = this; Self.products = Ko.observablearray ();
var BaseUri = ' @ViewBag. Apiurl ';
Self.create = function (formelement) {//If valid, post the serialized form data to the Web API If valid, submit the serialized form data (POST) to the Web API $ (formelement). Validate (); if ($ (formelement). Valid ()) {$.post (BaseUri, $ (formelement). Serialize (), NULL, "JSON") . Done (function (o) {Self.products.push (o);}); } }
Self.update = function (product) {$.ajax ({type: "PUT", Url:baseuri + '/' + product. Id, data:product}); }
Self.remove = function (product) {//First remove from the server and then from the UI//removed from server , and then remove $.ajax from the UI ({type: "delete", Url:baseuri + '/' + product. Id}). Done (function () {self.products.remove (product);}); }
$.getjson (BaseUri, self.products); }
$ (document). Ready (function () {ko.applybindings (New Productsviewmodel ()); }) </script>}
<div class= "Float-right" > Run the application, log in with the Administrator account, and click the "Admin" link. You should see the list of products, and is able to create, update, or delete products.
Run the application, log in with the Administrator account, and click on the "Admin" link. You should see a list of products and be able to create, update, or delete products.
Read this article if you feel something rewarding, please give a recommendation
Reference page:
Http://www.yuanjiaocheng.net/CSharp/Csharp-do-while-loop.html
Http://www.yuanjiaocheng.net/mvc/viewdata-in-asp.net-mvc.html
Http://www.yuanjiaocheng.net/mvc/htmlhelper-validationmessagefor.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-dbcontext.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-Generics-collection.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-hanling-exception.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-while-loop.html
Http://www.yuanjiaocheng.net/mvc/integrate-controller-view-model.html
Http://www.yuanjiaocheng.net/CSharp/csharp-var.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-operators.html
Http://www.yuanjiaocheng.net/webapi/web-api-gaisu.html
ASP. NET Web API tutorial 2.3.5 creating dynamic UI with Knockout.js