【ASP.NET Web API教程】2.3.7 创建首页

简介: 原文:【ASP.NET Web API教程】2.3.7 创建首页注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。 Part 7: Creating the Main Page 第7部分:创建首页 本文引自:http://www.
原文: 【ASP.NET Web API教程】2.3.7 创建首页

注:本文是【ASP.NET Web API系列教程】的一部分,如果您是第一次看本博客文章,请先看前面的内容。

Part 7: Creating the Main Page
第7部分:创建首页

本文引自:http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/using-web-api-with-entity-framework,-part-7

Creating the Main Page
创建首页

In this section, you will create the main application page. This page will be more complex than the Admin page, so we’ll approach it in several steps. Along the way, you'll see some more advanced Knockout.js techniques. Here is the basic layout of the page:
在这一小节中将创建主应用程序的首页。这个页面要比Admin页面更复杂些。因此,我们将采用几个步骤。在此过程中,你将看到一些更高级的Knockout.js技术。以下是此页面的基本布局(见图2-26):

WebAPI2-26

图2-26. 首页布局

  • "Products" holds an array of products.
    “产品”放置产品数组。
  • "Cart" holds an array of products with quantities. Clicking “Add to Cart” updates the cart.
    “购物车”放置带有订购数的产品数组。点击“加入购物车”会对购物车进行更新。
  • "Orders" holds an array of order IDs.
    “订单”放置订单的ID数组(订单号数组)。
  • "Details" holds an order detail, which is an array of items (products with quantities)
    “细节”放置一份订单细节,这是一个条目数组(带有订购数的产品)。

We’ll start by defining some basic layout in HTML, with no data binding or script. Open the file Views/Home/Index.cshtml and replace all of the contents with the following:
我们将以无数据的绑定或脚本首先定义一些HTML的基本布局。打开Views/Home/Index.cshtml文件,并将全部内容替换如下:

<div class="content"> 
    <!-- List of products(产品列表) --> 
    <div class="float-left"> 
    <h1>Products</h1> 
    <ul id="products"> 
    </ul> 
    </div> 
    <!—Cart(购物车) --> 
    <div id="cart" class="float-right"> 
    <h1>Your Cart</h1> 
        <table class="details ui-widget-content"> 
    </table> 
    <input type="button" value="Create Order"/> 
    </div> 
</div> 
<div id="orders-area" class="content" > 
    <!-- List of orders --> 
    <div class="float-left"> 
    <h1>Your Orders</h1> 
    <ul id="orders"> 
    </ul> 
    </div> 
   <!-- Order Details(订单细节) --> 
    <div id="order-details" class="float-right"> 
    <h2>Order #<span></span></h2> 
    <table class="details ui-widget-content"> 
    </table> 
    <p>Total: <span></span></p> 
    </div> 
</div>

Next, add a Scripts section and create an empty view-model:
下一步,添加一个脚本片段,并创建一个空的视图模型:

@section Scripts { 
  <script type="text/javascript" src="@Url.Content("~/Scripts/knockout-2.1.0.js")"></script> 
  <script type="text/javascript"> 
    function AppViewModel() { 
        var self = this; 
        self.loggedIn = @(Request.IsAuthenticated ? "true" : "false"); 
    } 
    $(document).ready(function () { 
        ko.applyBindings(new AppViewModel()); 
    }); 
  </script> 
}

Based on the design sketched earlier, our view model needs observables for products, cart, orders, and details. Add the following variables to the AppViewModel object:
基于前面的设计框架,我们的视图需要产品、购物车、订单以及订单细节的可见对象(observables)。将以下变量添加到AppViewModel对象:

self.products = ko.observableArray(); 
self.cart = ko.observableArray(); 
self.orders = ko.observableArray(); 
self.details = ko.observable();

Users can add items from the products list into the cart, and remove items from the cart. To encapsulate these functions, we'll create another view-model class that represents a product. Add the following code to AppViewModel:
用户可以把产品列表中的条目添加到购物车中,以及从购物车删除条目。为了封装这些函数,我们将创建另一个表示产品的视图模型类。将以下代码添加到AppViewModel

function AppViewModel() { 
    // ... 
    // NEW CODE 
    // 新代码
    function ProductViewModel(root, product) { 
        var self = this; 
        self.ProductId = product.Id; 
        self.Name = product.Name; 
        self.Price = product.Price; 
        self.Quantity = ko.observable(0); 
        self.addItemToCart = function () { 
            var qty = self.Quantity(); 
            if (qty == 0) { 
                root.cart.push(self); 
            } 
            self.Quantity(qty + 1); 
        }; 
        self.removeAllFromCart = function () { 
            self.Quantity(0); 
            root.cart.remove(self); 
        }; 
    } 
}

The ProductViewModel class contains two functions that are used to move the product to and from the cart: addItemToCart adds one unit of the product to the cart, and removeAllFromCart removes all quantities of the product.
这个ProductViewModel类包含两个函数,用于对购物车添加或删除产品:addItemToCart将一个产品单位添加到购物车(即,产品订购数加1 — 译者注),而removeAllFromCart删除产品的全部订购数。

Users can select an existing order and get the order details. We'll encapsulate this functionality into another view-model:
用户可以选择一个已有订单,并获取该订单细节。我们将把这个功能封装到另一个视图模型之中:

function AppViewModel() { 
    // ... 
    // NEW CODE 
    // 新代码
    function OrderDetailsViewModel(order) { 
        var self = this; 
        self.items = ko.observableArray(); 
        self.Id = order.Id; 
        self.total = ko.computed(function () { 
            var sum = 0; 
            $.each(self.items(), function (index, item) { 
                sum += item.Price * item.Quantity; 
            }); 
            return '$' + sum.toFixed(2); 
        }); 
        $.getJSON("/api/orders/" + order.Id, function (order) { 
            $.each(order.Details, function (index, item) { 
                self.items.push(item); 
            }) 
        }); 
    }; 
}

The OrderDetailsViewModel is initialized with an order, and it fetches the order details by sending an AJAX request to the server.
OrderDetailsViewModel用一个订单进行初始化,并能通过向服务器发送一个AJAX请求来捕捉该订单的细节。

Also, notice the total property on the OrderDetailsViewModel. This property is a special kind of observable called a computed observable. As the name implies, a computed observable lets you data bind to a computed value—in this case, the total cost of the order.
另外,要注意到OrderDetailsViewModel上的total属性。这个属性是一个叫做“已计算可见对象”的特殊类型的可见对象。正如其名称所暗示的那样,一个已计算可见对象可以让你把数据绑定到一个已计算的值 — 在此例中是订单的总费用(total cost)。

Next, add these functions to AppViewModel:
接下来,把这些函数添加到AppViewModel

  • resetCart removes all items from the cart.
    resetCart删除购物车的所有条目。
  • getDetails gets the details for an order (by pusing pushing a new OrderDetailsViewModel onto the details list).
    getDetails获取一份订单的细节(通过把一个新的OrderDetailsViewModel推入details列表)。
  • createOrder creates a new order and empties the cart.
    createOrder创建一个新的订单,并清空购物车。
function AppViewModel() { 
    // ... 
    // NEW CODE
    // 新代码
    self.resetCart = function() { 
        var items = self.cart.removeAll(); 
        $.each(items, function (index, product) { 
            product.Quantity(0); 
        }); 
    } 
    self.getDetails = function (order) { 
        self.details(new OrderDetailsViewModel(order)); 
    } 
    self.createOrder = function () { 
        var jqxhr = $.ajax({ 
            type: 'POST', 
            url: "api/orders", 
            contentType: 'application/json; charset=utf-8', 
            data: ko.toJSON({ Details: self.cart }), 
            dataType: "json", 
            success: function (newOrder) { 
                self.resetCart(); 
                self.orders.push(newOrder); 
            }, 
            error: function (jqXHR, textStatus, errorThrown) { 
                self.errorMessage(errorThrown); 
            }   
        }); 
    }; 
};

Finally, initialize the view model by making AJAX requests for the products and orders:
最后,通过发送对产品和订单的AJAX请求的办法,对这个视图模型进行初始化:

function AppViewModel() { 
    // ... 
    // NEW CODE 
    // 新代码
    // Initialize the view-model. 
    $.getJSON("/api/products", function (products) { 
        $.each(products, function (index, product) { 
            self.products.push(new ProductViewModel(self, product)); 
        }) 
    }); 
    $.getJSON("api/orders", self.orders); 
};

OK, that's a lot of code, but we built it up step-by-step, so hopefully the design is clear. Now we can add some Knockout.js bindings to the HTML.
好了,代码很多,但我们一步步把它建立起来了,希望这一设计是清晰的。现在,我们可以对这个HTML添加一些Knockout.js绑定。

Products
产品

Here are the bindings for the product list:
以下是对产品列表的绑定:

<ul id="products" data-bind="foreach: products"> 
    <li> 
        <div> 
            <span data-bind="text: Name"></span>  
            <span class="price" data-bind="text: '$' + Price"></span> 
        </div> 
        <div data-bind="if: $parent.loggedIn"> 
            <button data-bind="click: addItemToCart">Add to Order</button> 
        </div> 
    </li> 
</ul>

This iterates over the products array and displays the name and price. The "Add to Order" button is visible only when the user is logged in.
它对产品数组进行了循环,并显示名称和价格。“加入购物车”按钮只在用户登录时才是可见的。

The "Add to Order" button calls addItemToCart on the ProductViewModel instance for the product. This demonstrates a nice feature of Knockout.js: When a view-model contains other view-models, you can apply the bindings to the inner model. In this example, the bindings within the foreach are applied to each of the ProductViewModel instances. This approach is much cleaner than putting all of the functionality into a single view-model.
“加入购物车”按钮针对(所选)产品调用ProductViewModel实例上的addItemToCart。这演示了Knockout.js的一个很好的特性:当一个视图模型含有其它视图模型时,你可以把绑定运用于内部模型。在这个例子中,在foreach中的绑定被运用于每个ProductViewModel实例。这种办法要比把所有功能放在一个单一的视图模型中要清晰得多。

Cart
购物车

Here are the bindings for the cart:
以下是对购物车的绑定:

<div id="cart" class="float-right" data-bind="visible: cart().length > 0"> 
<h1>Your Cart</h1> 
    <table class="details ui-widget-content"> 
    <thead> 
        <tr><td>Item</td><td>Price</td><td>Quantity</td><td></td></tr> 
    </thead>     
    <tbody data-bind="foreach: cart"> 
        <tr> 
            <td><span data-bind="text: $data.Name"></span></td> 
            <td>$<span data-bind="text: $data.Price"></span></td> 
            <td class="qty"><span data-bind="text: $data.Quantity()"></span></td> 
            <td><a href="#" data-bind="click: removeAllFromCart">Remove</a></td> 
        </tr> 
    </tbody> 
</table> 
<input type="button" data-bind="click: createOrder" value="Create Order"/>

This iterates over the cart array and displays the name, price, and quantity. Note that the "Remove" link and the "Create Order" button are bound to view-model functions.
这是对购物车的循环,并且显示名称、价格和数据。注意,“删除”链接和“创建订单”按钮都被绑定到视图模型的函数上。

Orders
订单

Here are the bindings for the orders list:
以下是对订单列表的绑定:

<h1>Your Orders</h1> 
<ul id="orders" data-bind="foreach: orders"> 
<li class="ui-widget-content"> 
    <a href="#" data-bind="click: $root.getDetails"> 
        Order # <span data-bind="text: $data.Id"></span></a> 
</li> 
</ul>

This iterates over the orders and shows the order ID. The click event on the link is bound to the getDetails function.
它对订单进行了循环,并显示订单ID。链接上的点击事件被绑定到getDetails函数。

Order Details
订单细节

Here are the bindings for the order details:
以下是对订单细节的绑定:

<div id="order-details" class="float-right" data-bind="if: details()"> 
<h2>Order #<span data-bind="text: details().Id"></span></h2> 
<table class="details ui-widget-content"> 
    <thead> 
        <tr><td>Item</td><td>Price</td><td>Quantity</td><td>Subtotal</td></tr> 
    </thead>     
    <tbody data-bind="foreach: details().items"> 
        <tr> 
            <td><span data-bind="text: $data.Product"></span></td> 
            <td><span data-bind="text: $data.Price"></span></td> 
            <td><span data-bind="text: $data.Quantity"></span></td> 
            <td> 
                <span data-bind="text: ($data.Price * $data.Quantity).toFixed(2)"></span> 
            </td> 
        </tr> 
    </tbody> 
</table> 
<p>Total: <span data-bind="text: details().total"></span></p> 
</div>

This iterates over the items in the order and displays the product, price, and quanity quantity. The surrounding div is visible only if the details array contains one or more items.
它对订单中的条目进行循环,并显示产品、价格和数量。div所包围的部分只在订单细节数组含有一个或多个条目时才会显示。

Conclusion
结论

In this tutorial, you created an application that uses Entity Framework to communicate with the database, and ASP.NET Web API to provide a public-facing interface on top of the data layer. We use ASP.NET MVC 4 to render the HTML pages, and Knockout.js plus jQuery to provide dynamic interactions without page reloads.
在这个教程中,你创建了一个应用程序,它用实体框架与数据库进行通信,并用ASP.NET Web API提供了一个建立在数据层之上的面向公众的接口。我们使用了ASP.NET MVC 4来渲染HTML页面,并用Knckout.js加jQuery来提供不必进行页面重载的动态交互。

Additional resources:
其它资源:

看完此文如果觉得有所收获,恳请给个推荐

目录
相关文章
|
1月前
|
JSON API 数据库
解释如何在 Python 中实现 Web 服务(RESTful API)。
解释如何在 Python 中实现 Web 服务(RESTful API)。
25 0
|
2月前
|
IDE Java API
使用Java Web技术构建RESTful API的实践指南
使用Java Web技术构建RESTful API的实践指南
|
1月前
|
XML JSON API
通过Flask框架创建灵活的、可扩展的Web Restful API服务
通过Flask框架创建灵活的、可扩展的Web Restful API服务
|
1月前
|
缓存 监控 API
Python Web框架FastAPI——一个比Flask和Tornada更高性能的API框架
Python Web框架FastAPI——一个比Flask和Tornada更高性能的API框架
57 0
|
1月前
|
JSON API 数据格式
构建高效Python Web应用:Flask框架与RESTful API设计实践
【2月更文挑战第17天】在现代Web开发中,轻量级框架与RESTful API设计成为了提升应用性能和可维护性的关键。本文将深入探讨如何使用Python的Flask框架来构建高效的Web服务,并通过具体实例分析RESTful API的设计原则及其实现过程。我们将从基本的应用架构出发,逐步介绍如何利用Flask的灵活性进行模块化开发,并结合请求处理、数据验证以及安全性考虑,打造出一个既符合标准又易于扩展的Web应用。
629 4
|
1月前
|
存储 PHP 数据库
使用Net2FTP轻松打造免费的Web文件管理器并公网远程访问
使用Net2FTP轻松打造免费的Web文件管理器并公网远程访问
|
2月前
|
前端开发 JavaScript API
前端秘法番外篇----学完Web API,前端才能算真正的入门
前端秘法番外篇----学完Web API,前端才能算真正的入门
|
2月前
|
API 网络架构
解释 RESTful API,以及如何使用它构建 web 应用程序。
解释 RESTful API,以及如何使用它构建 web 应用程序。
87 0
|
2月前
|
存储 前端开发 搜索推荐
前端开发中值得关注的三个Web API
【2月更文挑战第4天】Web API是前端开发中非常重要的一部分,它们为开发者提供了众多的功能和特性,帮助我们构建更加高效、优美的Web应用。本文将介绍三个值得关注的Web API,包括Web Storage、Geolocation和Web Notifications,希望能够对前端开发者有所帮助。
|
2月前
|
缓存 安全 API
深入理解Web开发中的RESTful API设计
在当今快速演进的技术世界中,RESTful API已成为构建现代Web应用不可或缺的一部分。它不仅促进了前后端的分离发展,还为不同平台间的数据交换提供了一种高效、标准化的方式。本文旨在深入探讨RESTful API的设计原则和最佳实践,通过具体示例说明如何设计易于维护、可扩展和安全的API。我们将从REST的基本概念出发,逐步深入到资源命名、HTTP方法的恰当使用、状态码的选择、以及安全性考虑等方面,为读者提供一个全面而深入的视角,帮助大家更好地理解和运用RESTful API。

热门文章

最新文章