码迷,mamicode.com
首页 > Windows程序 > 详细

一个简单的webAPI调用

时间:2018-05-08 16:24:37      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:spn   ajax   put   选择   search   color   var   span   models   

1.新建一个ASP.NET Web应用程序。

技术分享图片

2.选择空模板,WebAPI。

技术分享图片

3.在Models文件夹添加Product类。

技术分享图片

4.添加空控制器ProductController。

技术分享图片

5.ProductController控制器添加下面代码。

技术分享图片

6.添加一个Html页面。

技术分享图片
 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>Product App</title>
 5 </head>
 6 <body>
 7 
 8     <div>
 9         <h2>All Products</h2>
10         <ul id="products" />
11     </div>
12     <div>
13         <h2>Search by ID</h2>
14         <input type="text" id="prodId" size="5" />
15         <input type="button" value="Search" onclick="find();" />
16         <p id="product" />
17     </div>
18 
19     <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
20     <script>
21         var uri = api/Product;
22 
23     $(document).ready(function () {
24       // Send an AJAX request
25       $.getJSON(uri)
26           .done(function (data) {
27             // On success, ‘data‘ contains a list of products.
28             $.each(data, function (key, item) {
29               // Add a list item for the product.
30               $(<li>, { text: formatItem(item) }).appendTo($(#products));
31             });
32           });
33     });
34 
35     function formatItem(item) {
36       return item.Name + : $ + item.Price;
37     }
38 
39     function find() {
40       var id = $(#prodId).val();
41       $.getJSON(uri + / + id)
42           .done(function (data) {
43             $(#product).text(formatItem(data));
44           })
45           .fail(function (jqXHR, textStatus, err) {
46             $(#product).text(Error:  + err);
47           });
48     }
49     </script>
50 </body>
51 </html>
HTML

7.运行效果:

技术分享图片

具体来自于微软官方:https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

一个简单的webAPI调用

标签:spn   ajax   put   选择   search   color   var   span   models   

原文地址:https://www.cnblogs.com/Zhengxue/p/9008458.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!