ASP.NET WebAPI2第002天_創建第一個Model和Controller_jQuery實踐HTTP Get資料查詢顯示


對Model Folder右鍵新增一個Context 的 Class
在此我們用一個用戶的資料實體來練習



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApp.Models
{
    public class Context
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Context()
        {
            Id = -1;
            FirstName = string.Empty;
            LastName = string.Empty;
        }

    }
}

對Controller目錄新增一個Controller (注意!! 不是Class喔)


這裡我們已經知道Rest的知識因此就直接選擇具備讀取寫入的控制器項目

這裡習慣命名方式
你有哪個Model Context
就依照該Model的名稱後面加Controller


這樣就建好了

預設生成的程式碼


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApp.Controllers
{
    public class ContextController : ApiController
    {
        // GET: api/Context
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Context/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Context
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/Context/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Context/5
        public void Delete(int id)
        {
        }
    }
}

這裡修改一下進行模擬練習
我們創建一個Context的Array

並修改Get Method,由於我們希望能查詢瀏覽到用戶列
回傳型態改為contexts陣列


這裡我們要來弄個頁面





接著要發出Request,在此用jQuery來練習
(這裡透過Nuget來配置JQuery)


接著Drag jquery參考路徑 到 html Page


HTML & Js Code


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="Scripts/jquery-3.4.1.min.js"></script>
</head>
<body>
    <script type="text/javascript">
        $(document).ready(function () {
            $.getJSON("api/Context", function (result) {
                console.info(result);
            });
        });
    </script>
</body>
</html>

在此要記得是傳遞path給getJSON去處理

透過getJSON可以幫我們獲取HTTP Get請求發送回傳的
經由JSON編碼後的server端物件資料


接著運行開啟html F12切至Console就能看到回傳三個物件內容



在F12中我們也可查看其網路資訊來驗證文本講的Web API GET 請求
Filter選XHR就可以只看所發出的Web Service(API) Call

這裡也清楚可見GET 200 OK的Header訊息

這裡也再次驗證文本所講的Web API Route機制


Server端資料預覽
Server端資料回傳



留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

外貿Payment Term 付款條件(方式)常見的英文縮寫與定義

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題