1. 程式人生 > >使用 ASP.NET Core MVC 建立 Web API(六)

使用 ASP.NET Core MVC 建立 Web API(六)

使用 ASP.NET Core MVC 建立 Web API

使用 ASP.NET Core MVC 建立 Web API(一)

使用 ASP.NET Core MVC 建立 Web API(二)

 使用 ASP.NET Core MVC 建立 Web API(三)

使用 ASP.NET Core MVC 建立 Web API(四)

使用 ASP.NET Core MVC 建立 Web API(五)

十七、使用 jQuery 呼叫 API

    在之前的文章中我們是使用Rester來測試我們的WebAPI的。接下來,我們來建立一個實際的頁面來測試之前我們寫的WebAPI。我們建立一個HTML頁面,並在頁面使用 jQuery 來呼叫 Web API 。通過jQuery來呼叫增刪除改查WebAPI介面,並用 API 介面返回的響應中的詳細資訊更新到頁面中。

    1) 在Visual Studio 2017的“解決方案資源管理器”中開啟Startup.cs檔案,並找到Configure方法,在方法中新增 app.UseStaticFiles()方法,配置應用提供靜態檔案並啟用預設檔案對映,程式碼如下:     

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseMvc();
        }

    2) 在Visual Studio 2017的“解決方案資源管理器”中,選中解決方案,點選滑鼠右鍵,在彈出選單中選擇“新增—》新建資料夾”,並把“新資料夾”命名為 wwwroot。如下圖。

 

      3) 在Visual Studio 2017的“解決方案資源管理器”中,選中“wwwroot”目錄,點選滑鼠右鍵,在彈出選單中選擇“新增—》新建項”,在彈出對話方塊中選擇“HTML頁”,並在名稱輸入框中輸入“index.html”,然後點選“新增”按鈕。如下圖。

Index.html檔案的內容如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>BOOK CRUD</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 檔案 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- 最新的 Bootstrap 核心 JavaScript 檔案 --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> </head> <body> <h1>BOOK CRUD</h1> <div class="container-fluid"> <div class="row-fluid"> <div class="col-xs-12 col-md-8"> <p id="counter"></p> <table class="table table-bordered"> <tr> <th>ID</th> <th>Name</th> <th>ReleaseDate</th> <th>Author</th> <th>Price</th> <th>Publishing</th> <th colspan="2"> <a class="btn btn-default btn-xs" onclick="getData()" role="button">重新整理</a> </th> </tr> <tbody id="books"></tbody> </table> </div> <div class="col-md-2"> <form action="javascript:void(0);" method="POST" onsubmit="addItem()"> <fieldset> <legend>Add</legend> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label class="control-label">Name</label> <input id="AddName" class="form-control" /> </div> <div class="form-group"> <label class="control-label">ReleaseDate</label> <input id="AddReleaseDate" class="form-control" /> </div> <div class="form-group"> <label class="control-label">Author</label> <input id="AddAuthor" class="form-control" /> </div> <div class="form-group"> <label class="control-label">Price</label> <input id="AddPrice" class="form-control" /> </div> <div class="form-group"> <label class="control-label">Publishing</label> <input id="AddPublishing" class="form-control" /> </div> <div class="form-group"> <input type="submit" value="Add" class="btn btn-primary"> </div> </fieldset> </form> </div> <div class="col-md-2" id="spoiler"> <form class="my-form"> <fieldset> <legend>Edit</legend> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <input type="hidden" id="BookID" /> <input type="hidden" id="RowVersion" /> <div class="form-group"> <label class="control-label">Name</label> <input id="Name" class="form-control" /> </div> <div class="form-group"> <label class="control-label">ReleaseDate</label> <input id="ReleaseDate" class="form-control" /> </div> <div class="form-group"> <label class="control-label">Author</label> <input id="Author" class="form-control" /> </div> <div class="form-group"> <label class="control-label">Price</label> <input id="Price" class="form-control" /> </div> <div class="form-group"> <label class="control-label">Publishing</label> <input id="Publishing" class="form-control" /> </div> <div class="form-group"> <input type="submit" value="Save" class="btn btn-default" /> <a onclick="closeInput()" aria-label="Close">&#10006;</a> </div> </fieldset> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script src="site.js"></script> </body> </html>

 

    4) 在Visual Studio 2017的“解決方案資源管理器”中,選中“wwwroot”目錄,點選滑鼠右鍵,在彈出選單中選擇“新增—》新建項”,在彈出對話方塊中選擇“JavaScript檔案”,並在名稱輸入框中輸入“site.js”,然後點選“新增”按鈕。如下圖。

 

    5) 在site.js檔案中新增如下 程式碼:

const uri = "api/book";
let books = null;
function getCount(data) {
    const el = $("#counter");
    let name = "book";
    if (data) {
        if (data > 1) {
            name = "book-s";
        }

        el.text(data + " " + name);
    } else {
        el.text("No " + name);
    }
} 

$(document).ready(function () {
    getData();

}); 

function getData() {
    $.ajax({
        type: "GET",
        url: uri,
        cache: false,
        success: function (data) {
            const tBody = $("#books");
            $(tBody).empty();
            getCount(data.length);

            $.each(data, function (key, item) {
                const tr = $("<tr></tr>")
                    .append($("<td></td>").text(item.id))
                    .append($("<td></td>").text(item.name))
                    .append($("<td></td>").text(item.releaseDate))
                    .append($("<td></td>").text(item.author))
                    .append($("<td></td>").text(item.price))
                    .append($("<td></td>").text(item.publishing))
                    .append(
                        $("<td></td>").append(

  $("<button class=\"btn btn-default btn-sm\" >Edit</button>").on("click", function () {                                editItem(item.id);
                            })
                        )
                    )
                    .append(
                        $("<td></td>").append(

$("<button class=\"btn btn-default btn-sm\">Delete</button>").on("click", function () {                                deleteItem(item.id);
                            })
                        )
                    );
                tr.appendTo(tBody);
            });
            books = data;
        }
    });
} 

function addItem() {
    const item = {
        Name: $("#AddName").val(),
        ReleaseDate: $("#AddReleaseDate").val(),
        Author: $("#AddAuthor").val(),
        Publishing: $("#AddPublishing").val(),
        Price: $("#AddPrice").val(),     

        ID: 0
    }; 

    $.ajax({
        type: "POST",
        accepts: "application/json",
        url: uri,
        contentType: "application/json",
        data: JSON.stringify(item),
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Something went wrong!");
        },

        success: function (result) {
            getData();
            $("#add-name").val("");
        }
    });
} 

function deleteItem(id) {
    $.ajax({
        url: uri + "/" + id,
        type: "DELETE",
        success: function (result) {
            getData();
        }
    });
} 

function editItem(id) {
    $.each(books, function (key, item) {
        if (item.id === id) {
            $("#Name").val(item.name);
            $("#BookID").val(item.id);
            $("#ReleaseDate").val(item.releaseDate);

            $("#Author").val(item.author);
            $("#Publishing").val(item.publishing);
            $("#Price").val(item.price);
            $("#RowVersion").val(item.rowVersion);
        }
    });
    $("#spoiler").css({ display: "block" });
} 

$(".my-form").on("submit", function () {
    const item = {
        Name: $("#Name").val(),
        ReleaseDate: $("#ReleaseDate").val(),
        Author: $("#Author").val(),
        Publishing: $("#Publishing").val(),
        Price: $("#Price").val(),
        RowVersion: $("#RowVersion").val(),
        ID: $("#BookID").val()
    }; 

    $.ajax({
        url: uri + "/" + $("#BookID").val(),
        type: "PUT",
        accepts: "application/json",
        contentType: "application/json",
        data: JSON.stringify(item),
        success: function (result) {
            getData();
        }
    }); 

    closeInput();
    return false;
}); 

function closeInput() {
    $("#spoiler").css({ display: "none" });
}

 

     6) 修改 ASP.NET Core 專案的啟動設定,以便對 HTML 頁面進行本地測試。在Visual Studio 2017中開啟 Properties\launchSettings.json。

     7) 刪除 launchUrl 以便在專案的預設檔案 index.html 強制開啟應用。如下圖。

 

     此示例呼叫 API 的所有 CRUD 方法。 以下是 API 呼叫的說明。

    一)獲取書籍的列表

     我們寫的指令碼中的getData 方法是通過jQuery ajax 函式將 GET 請求傳送至 BookApi應用程式的GetBookItem方法,這個方法返回表示書籍陣列的 JSON。 如果請求成功,則呼叫 success 回撥函式。在該回調中將書籍資訊組裝成表格更新到 DOM中。如下圖。

 

     二)新增書籍資訊

     指令碼中的addItem 方法通過JQuery 的Ajax 函式傳送 POST請求,請求正文中包含書籍資訊。 將 acceptscontentType 選項設定為 application/json,以便指定接收和傳送的資料型別。 書籍資訊使用 JSON.stringify 轉換為 JSON。 當 API 返回成功狀態的程式碼時,將呼叫 getData 函式來更新 HTML 表格。如下圖。 

     三)  更新書籍資訊

     editItem方法用來更新書籍資訊,這個方法的實現與addItem類似。 url 更改為新增項的唯一識別符號,並且 typePUT。如下圖。我們在表格點選需要修改的書籍資訊的“Edit”按鈕,系統會把這條書籍資訊中的資料顯示到編輯文字框中,在進行修改之後,點選“Save”按鈕,儲存資料。

     四) 刪除書籍

      deleteItem方法用來刪除書籍資訊,通過呼叫JQuery  AJAX函式發出刪除請求。並把 type 設為 DELETE ,指定該項在 URL 中的唯一識別符號。如下圖中1與2,就是刪除前後的情況。我們點選表格中的刪除按鈕,將呼叫指令碼中的deleteItem方法,刪除指定書籍。

 

&n