日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > asp.net >内容正文

asp.net

【ASP.NET Web API教程】2.3.5 用Knockout.js创建动态UI

發(fā)布時(shí)間:2024/4/17 asp.net 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【ASP.NET Web API教程】2.3.5 用Knockout.js创建动态UI 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
【ASP.NET Web API教程】2.3.5 用Knockout.js創(chuàng)建動(dòng)態(tài)UI 原文:【ASP.NET Web API教程】2.3.5 用Knockout.js創(chuàng)建動(dòng)態(tài)UI

注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,請(qǐng)先看前面的內(nèi)容。

Part 5: Creating a Dynamic UI with Knockout.js
第5部分:用Knockout.js創(chuàng)建動(dòng)態(tài)UI

本文引自: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
用Knockout.js創(chuàng)建動(dòng)態(tài)UI

In this section, we'll use Knockout.js to add functionality to the Admin view.
在本小節(jié)中,我們將用Knockout.js對(duì)Admin視圖添加功能。

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.
Knockout.js是一個(gè)JavaScript庫(kù),它讓HTML控件很容易與數(shù)據(jù)進(jìn)行綁定。Knockout.js使用的是“模型-視圖-視圖模型(MVVM)”模式。

  • The model is the server-side representation of the data in the business domain (in our case, products and orders).
    模型是事務(wù)域中數(shù)據(jù)的服務(wù)器端表示(在我們的示例中,是產(chǎn)品和訂單)。
  • The view is the presentation layer (HTML).
    視圖是表現(xiàn)層(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".
    視圖模型是保存了模型數(shù)據(jù)的一個(gè)JavaScript對(duì)象。視圖模型是UI的一種代碼抽象。它沒(méi)有HTML表示方面的知識(shí),但它表現(xiàn)了視圖的抽象特性,如“列表項(xiàng)”。

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.
視圖是與視圖模型數(shù)據(jù)綁定的。對(duì)視圖模型的更新會(huì)自動(dòng)地在視圖得到反映。視圖模型也會(huì)獲取視圖的事件,如按鈕點(diǎn)擊,并在模型上執(zhí)行操作(見(jiàn)圖2-23)。

圖2-23. 模型-視圖-視圖模型之間的關(guān)系

First we'll define the view-model. After that, we will bind the HTML markup to the view-model.
首先,我們要定義視圖模型。之后,要將HTML標(biāo)記與視圖模型進(jìn)行綁定。

Add the following Razor section to Admin.cshtml:
對(duì)Admin.cshtml添加以下Razor片段:

@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 will go here // 視圖模型會(huì)放在這兒</script> }

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.
可以把這個(gè)片斷添加到文件的任何地方。當(dāng)視圖被渲染時(shí),這個(gè)片段會(huì)出現(xiàn)在HTML頁(yè)面的底部,</body>關(guān)閉標(biāo)簽的前面。

All of the script for this page will go inside the script tag indicated by the comment:
用于這個(gè)頁(yè)面的所有腳本都被放在由以下注釋所指示的script標(biāo)簽中:

<script type="text/javascript"> // View-model will go here// 視圖模型會(huì)放在這兒</script>

First, define a view-model class:
首先,定義一個(gè)視圖模型類:

function ProductsViewModel() { var self = this; self.products = ko.observableArray(); }

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.
ko.observableArray是Knockout中的一種叫做observable的特殊對(duì)象(請(qǐng)將這種observable對(duì)象稱為可見(jiàn)對(duì)象。這種對(duì)象往往作為視圖模型與視圖進(jìn)行交互,對(duì)視圖而言,它是透明可見(jiàn)的,故稱為可見(jiàn)對(duì)象。在以下翻譯中,都將這種observable對(duì)象稱為可見(jiàn)對(duì)象 — 譯者注)。根據(jù)Knockout.js文檔的描述:可見(jiàn)對(duì)象是一種“能夠通知訂戶數(shù)據(jù)變化情況的JavaScript對(duì)象”。當(dāng)一個(gè)可見(jiàn)對(duì)象的內(nèi)容發(fā)生變化時(shí),視圖會(huì)自動(dòng)地進(jìn)行匹配更新。

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).
為了填充Products數(shù)組,需要形成一個(gè)發(fā)送到Web API的請(qǐng)求。調(diào)回我們?cè)谝晥D包(View Bag)中存儲(chǔ)的、用于此API的基URI(見(jiàn)本教程的第4部分)。

function ProductsViewModel() { var self = this; self.products = ko.observableArray();
// 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 and use the results to update the view-model.
下一步,對(duì)視圖模型添加創(chuàng)建、更新以及刪除產(chǎn)品的函數(shù)。這些函數(shù)會(huì)對(duì)Web API遞交AJAX調(diào)用,并使用(所得到的)結(jié)果對(duì)視圖模型進(jìn)行更新。

function ProductsViewModel() { var self = 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.// 如果表單數(shù)據(jù)有效,把序列化的表單數(shù)據(jù)遞交給Web API$(formElement).validate(); if ($(formElement).valid()) { $.post(baseUri, $(formElement).serialize(), null, "json") .done(function (o) { // Add the new product to the view-model.// 將新產(chǎn)品添加到視圖模型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, then from the view-model.// 首先從服務(wù)器刪除,然后從視圖模型刪除$.ajax({ type: "DELETE", url: baseUri + '/' + product.Id }) .done(function () { self.products.remove(product); }); }
$.getJSON(baseUri, self.products); }

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:
現(xiàn)在,最重要的部分:當(dāng)DOM全部裝載時(shí),調(diào)用ko.applyBindings函數(shù),并在其中傳遞一個(gè)新的ProductsViewModel實(shí)例:

$(document).ready(function () {ko.applyBindings(new ProductsViewModel()); })

The ko.applyBindings method activates Knockout and wires up the view-model to the view.
ko.applyBindings方法會(huì)激活Knockout,并將視圖模型與視圖連接起來(lái)。

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:
現(xiàn)在,我們有了一個(gè)視圖模型,于是可以創(chuàng)建綁定(這里的綁定含義是將視圖模型中的數(shù)據(jù)項(xiàng)與視圖中的各個(gè)HTML控件進(jìn)行綁定 — 譯者注)。在Knockout.js中,通過(guò)把data-bind標(biāo)簽屬性(標(biāo)簽屬性是指HTML元素的屬性,這樣翻譯的目的也是與類的屬性有所區(qū)別 — 譯者注)添加到HTML元素的辦法來(lái)做這件事。例如,要把一個(gè)HTML列表綁定到一個(gè)數(shù)據(jù),使用foreach綁定:

<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.
foreach綁定會(huì)遍歷數(shù)組,并為數(shù)組中的每個(gè)對(duì)象創(chuàng)建子元素。在子元素上的綁定可以指向數(shù)組對(duì)象上的屬性。

Add the following bindings to the "update-products" list:
對(duì)“update-products”列表添加以下綁定:

<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> <!-- 這里的$表示的美元符字符 — 譯者注 --><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="click: $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 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.
<li>元素出現(xiàn)在foreach綁定的范圍之內(nèi)。這意味著Knockout會(huì)對(duì)products數(shù)組中的每個(gè)產(chǎn)品渲染一個(gè)元素。在<li>元素中的所有綁定指向這個(gè)產(chǎn)品實(shí)例。例如,$data.Name是指該產(chǎn)品上的Name屬性。

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.
設(shè)置文本輸入框的值,要使用value綁定。按鈕要綁定到視圖模型上的函數(shù),需使用click綁定。產(chǎn)品實(shí)例是作為參數(shù)傳遞給每個(gè)函數(shù)的。對(duì)于更多信息,Knockout.js文檔對(duì)各種綁定有很好的描述。

Next, add a binding for the submit event on the Add Product form:
下一步,為“添加產(chǎn)品”表單上的submit(遞交)事件添加一個(gè)綁定:

<form id="addProduct" data-bind="submit: create">

This binding calls the create function on the view-model to create a new product.
這個(gè)綁定調(diào)用視圖模型上的create函數(shù),以創(chuàng)建一個(gè)新產(chǎn)品。

Here is the complete code for the Admin view:
以下是Admin視圖的完整代碼:

@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 self = this; self.products = ko.observableArray();
var baseUri = '@ViewBag.ApiUrl';
self.create = function (formElement) { // If valid, post the serialized form data to the web api// 如果有效,把序列化的表單數(shù)據(jù)遞交(post)給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, then from the UI// 先從服務(wù)器刪除,然后從UI刪除$.ajax({ type: "DELETE", url: baseUri + '/' + product.Id }) .done(function () { self.products.remove(product); }); }
$.getJSON(baseUri, self.products); }
$(document).ready(function () { ko.applyBindings(new ProductsViewModel()); }) </script> }
<h2>Admin</h2> <div class="content"> <div class="float-left"> <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> <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="click: $root.update"/> <input type="button" value="Delete Item" data-bind="click: $root.remove"/> </div> </li> </ul> </div>
<div class="float-right"> <h2>Add New Product</h2> <form id="addProduct" data-bind="submit: create"> @Html.ValidationSummary(true) <fieldset> <legend>Contact</legend> @Html.EditorForModel() <p> <input type="submit" value="Save" /> </p> </fieldset> </form> </div> </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.
運(yùn)行應(yīng)用程序,用Administrator賬號(hào)登錄,并點(diǎn)擊“Admin”鏈接。應(yīng)當(dāng)看到產(chǎn)品列表,并能夠創(chuàng)建、更新或刪除產(chǎn)品。

看完此文如果覺(jué)得有所收獲,懇請(qǐng)給個(gè)推薦

posted on 2014-02-22 14:23 NET未來(lái)之路 閱讀(...) 評(píng)論(...) 編輯 收藏

轉(zhuǎn)載于:https://www.cnblogs.com/lonelyxmas/p/3560770.html

總結(jié)

以上是生活随笔為你收集整理的【ASP.NET Web API教程】2.3.5 用Knockout.js创建动态UI的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。