上一篇介紹了ASP.NET Web API的基本知識和原理,這一篇我們通過一個更直觀的實例,對產品進行CRUD操作(Create/Read/Update/Delete)來繼續了解一下它的基本應用。
創建ASP.NET Web API應用程序
在VS中選擇創建一個ASP.NET Web Application應用程序,在向導的下一個窗口中選擇Web API模板。

創建Model
這里我們在Models文件夾下創建一個簡單的Product model類,用來傳遞數據。
在Models文件夾上點擊右鍵,選擇Add -> Class
public class Product { public int ProductID { get; set; } public string ProductName { get; set; } public decimal Price { get; set; } public int Count { get; set; } public string Description { get; set; } }
創建Controller
接着在Controllers文件夾下創建一個API Controller, 命名為"ProductsController"。
在Controllers文件夾上點擊右鍵,選擇Add -> Controller ,在彈出向導中選擇Web API 2 Controller - Empty

在向導下一步中輸入API Controller name為"ProductsController"。

創建Web API方法(CRUD)並通過JQuery和Ajax進行數據操作
1.獲取Product列表
首先打開ProductsController文件,添加模擬數據以及獲取Product列表的方法。
public class ProductsController : ApiController { // Mock product list static List<Product> productMockList = initProductMockDataList(); private static List<Product> initProductMockDataList() { return new List<Product>() { new Product {ProductID=1,ProductName="Product A",Price=1000000,Count=5,Description="Description A"}, new Product {ProductID=2,ProductName="Product B",Price=200000,Count=2,Description="Description B"}, new Product {ProductID=3,ProductName="Product C",Price=500000,Count=8,Description="Description C"}, new Product {ProductID=4,ProductName="Product D",Price=80000,Count=10,Description="Description D"}, new Product {ProductID=5,ProductName="Product E",Price=300000,Count=3,Description="Description E"} }; } // GET api/products public IEnumerable<Product> GetAllProducts() { return productMockList; } }
接着在文件夾Views->Product下創建一個View,名為"Index"。這里我們需要實現的是點擊Get Product List按鈕獲取Product List數據,修改代碼如下:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script> </head> <body> <p><h2>ASP.NET Web API (CRUD)</h2></p> <div> <input id="btnGetProductList" name="btnGetProductList" type="button" value="Get Product List" /> <div id="productsBlock" style="padding-top:10px;display:none;"> <div style="padding-left:5px;">Product List</div> <div id="products"></div> </div> </div> <script> // Click get product list $('#btnGetProductList').click(function () { LoadProductList(); }); // Load product list function LoadProductList() { $.ajax({ url: '/api/products', contentType: 'application/html; charset=utf-8', type: 'GET', dataType: 'json' }).success(function (result) { $('#productsBlock').show(); DisplayProductList(result); }).error(function (data) { alert(data); }); } // Display product list function DisplayProductList(result) { var productTable = $("<table cellpadding='5' cellspacing='5'></table>"); var productTableTitle = $("<tr style='background-color:#7FBA00;'><th>Product ID</th><th>Product Name</th><th>Price</th><th>Count</th><th>Description</th></tr>"); productTableTitle.appendTo(productTable); for (var i = 0; i < result.length; i++) { var productTableContent = $("<tr style='background-color: #7FBA00; color: white;'><td>" + result[i].ProductID + "</td><td>" + result[i].ProductName + "</td><td>" + result[i].Price + "</td><td>" + result[i].Count + "</td><td>" + result[i].Description + "</td></tr>"); productTableContent.appendTo(productTable); } $('#products').html(productTable); } </script> </body> </html>
運行代碼,點擊Get Product List按鈕之前。

點擊Get Product List按鈕之后

2.獲取一條Product數據
這里我們的做法是點擊列表右側View鏈接,獲取當前Product數據,並顯示到列表下方各個字段對應的文本框中。
首先我們先完成Web API中獲取一條Product數據的方法。
// GET api/products/? public Product GetProdcut(int id) { return productMockList.Where(p => p.ProductID == id).FirstOrDefault(); }
接着,在Product列表中添加一列View,在列表下面添加對應各個字段的textbox。實現點擊View鏈接,獲取當前Product數據,然后顯示到對應的文本框中。
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script> </head> <body> <p><h2>ASP.NET Web API (CRUD)</h2></p> <div> <input id="btnGetProductList" name="btnGetProductList" type="button" value="Get Product List" /> <div id="productsBlock" style="padding-top:10px;display:none;"> <div style="padding-left:5px;">Product List</div> <div id="products"></div> <div id="editProductBlock" style="padding:10px;width:20%;border:1px solid green;display:none;"> <div style="font-weight:bold;">Edit Product</div> <table> <tr><td>Product ID:</td><td><input id="txtProductID" name="txtProductID" type="text" disabled /></td></tr> <tr><td> Product Name:</td><td><input id="txtProductName" name="txtProductName" type="text" /></td></tr> <tr><td>Count:</td><td><input id="txtCount" name="txtCount" type="text" /></td></tr> <tr><td> Price:</td><td><input id="txtPrice" name="txtPrice" type="text" /></td></tr> <tr><td> Description:</td><td><input id="txtDescription" name="txtDescription" type="text" /></td></tr> </table> <div style="padding-top:5px;"> <div id="message" style="color:green;"></div> <input id="btnSave" name="btnSave" type="button" value="Save" /> </div> </div> </div> </div> <script> // Click get product list $('#btnGetProductList').click(function () { LoadProductList(); }); // Load product list function LoadProductList() { $.ajax({ url: '/api/products', contentType: 'application/html; charset=utf-8', type: 'GET', dataType: 'json' }).success(function (result) { $('#productsBlock').show(); DisplayProductList(result); }).error(function (data) { alert(data); }); } // Display product list function DisplayProductList(result) { var productTable = $("<table cellpadding='5' cellspacing='5'></table>"); var productTableTitle = $("<tr style='background-color:#7FBA00;'><th>Product ID</th><th>Product Name</th><th>Price</th><th>Count</th><th>Description</th><th></th></tr>"); productTableTitle.appendTo(productTable); for (var i = 0; i < result.length; i++) { var productTableContent = $("<tr style='background-color: #7FBA00; color: white;'><td>" + result[i].ProductID + "</td><td>" + result[i].ProductName + "</td><td>" + result[i].Price + "</td><td>" + result[i].Count + "</td><td>" + result[i].Description + "</td>" + "<td><a href='#' onclick='ViewProduct(" + result[i].ProductID + ")'>View</a></td></tr>"); productTableContent.appendTo(productTable); } $('#products').html(productTable); } // View product function ViewProduct(productId) { $('#editProductBlock').show(); $.ajax({ url: '/api/products/' + productId, contentType: 'application/html;charset=utf-8', type:'GET' }).success(function (result) { if (result != null) { $("#txtProductID").val(result.ProductID); $("#txtProductName").val(result.ProductName); $("#txtCount").val(result.Count); $("#txtPrice").val(result.Price); $("#txtDescription").val(result.Description); } }).error(function (data) { alert(data); }) } </script> </body> </html>
運行程序
點擊Get Product List按鈕獲取列表數據,顯示如下。

接着點擊列表中任意記錄右邊的View鏈接,這里我們點擊第一條數據View鏈接,顯示如下。

3.新增一條Product
這里我們需要一個Create Product的按鈕,然后利用上面創建的TextBox來實現新增數據功能。
首先我們先完成Web API中新增Product數據的方法。
// POST api/products public void CreateProduct([FromBody]Product product) { var lastProduct = productMockList.OrderByDescending(p => p.ProductID).FirstOrDefault(); int newProductID = lastProduct.ProductID + 1; product.ProductID = newProductID; productMockList.Add(product); }
接着我們修改Index View頁面實現新增Product。
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script> </head> <body> <p><h2>ASP.NET Web API (CRUD)</h2></p> <div> <input id="btnGetProductList" name="btnGetProductList" type="button" value="Get Product List" /> <div id="productsBlock" style="padding-top:10px;display:none;"> <div style="padding-left:5px;">Product List</div> <div id="products"></div> <div> <input id="btnCreateProduct" name="btnCreateProduct" type="button" value="Create Product" /> </div> <div id="editProductBlock" style="padding:10px;width:20%;border:1px solid green;display:none;"> <div id="typeBlock" style="font-weight:bold;">Edit Product</div> <table> <tr><td>Product ID:</td><td><input id="txtProductID" name="txtProductID" type="text" disabled /></td></tr> <tr><td> Product Name:</td><td><input id="txtProductName" name="txtProductName" type="text" /></td></tr> <tr><td>Count:</td><td><input id="txtCount" name="txtCount" type="text" /></td></tr> <tr><td> Price:</td><td><input id="txtPrice" name="txtPrice" type="text" /></td></tr> <tr><td> Description:</td><td><input id="txtDescription" name="txtDescription" type="text" /></td></tr> </table> <div style="padding-top:5px;"> <div id="message" style="color:green;"></div> <input id="btnSave" name="btnSave" type="button" value="Save" /> <input id="btnCreate" name="btnCreate" type="button" value="Create"/> </div> </div> </div> </div> <script> // Click get product list $('#btnGetProductList').click(function () { LoadProductList(); }); // Load product list function LoadProductList() { $.ajax({ url: '/api/products', contentType: 'application/html; charset=utf-8', type: 'GET', dataType: 'json' }).success(function (result) { $('#productsBlock').show(); DisplayProductList(result); }).error(function (data) { alert(data); }); } // Display product list function DisplayProductList(result) { var productTable = $("<table cellpadding='5' cellspacing='5'></table>"); var productTableTitle = $("<tr style='background-color:#7FBA00;'><th>Product ID</th><th>Product Name</th><th>Price</th><th>Count</th><th>Description</th><th></th></tr>"); productTableTitle.appendTo(productTable); for (var i = 0; i < result.length; i++) { var productTableContent = $("<tr style='background-color: #7FBA00; color: white;'><td>" + result[i].ProductID + "</td><td>" + result[i].ProductName + "</td><td>" + result[i].Price + "</td><td>" + result[i].Count + "</td><td>" + result[i].Description + "</td>" + "<td><a href='#' onclick='ViewProduct(" + result[i].ProductID + ")'>View</a></td></tr>"); productTableContent.appendTo(productTable); } $('#products').html(productTable); } // View product function ViewProduct(productId) { $('#editProductBlock').show(); $('#btnCreate').hide(); $.ajax({ url: '/api/products/' + productId, contentType: 'application/html;charset=utf-8', type: 'GET' }).success(function (result) { if (result != null) { $("#txtProductID").val(result.ProductID); $("#txtProductName").val(result.ProductName); $("#txtCount").val(result.Count); $("#txtPrice").val(result.Price); $("#txtDescription").val(result.Description); } }).error(function (data) { alert(data); }); } $('#btnCreateProduct').click(function () { $('#editProductBlock').show(); $('#btnCreate').show(); $('#btnSave').hide(); $('#typeBlock').html("Create Product"); }); // Create product $('#btnCreate').click(function () { var product = { ProductID: 0, ProductName: $('#txtProductName').val(), Price: $('#txtPrice').val(), Count: $('#txtCount').val(), Description: $('#txtDescription').val() }; $.ajax({ url: '/api/products/', type: 'POST', data: JSON.stringify(product), contentType: 'application/json' }).success(function (result) { LoadProductList(); $('#message').html("Product create success."); }).error(function (data) { alert(data); }); }); </script> </body> </html>
運行程序
點擊獲取列表

點擊Create Product按鈕,輸入新增的Product數據。

點擊Create按鈕,結果如下圖。

4.修改Product信息
我們這里要實現的是點擊列表數據中的View鏈接,在文本框中修改選擇的Product信息,然后點擊Save按鈕,數據修改成功。
首先我們先完成Web API中修改Product數據的方法。
// PUT api/products public void UpdateProduct(int id,[FromBody]Product product) { var currentProduct = productMockList.Where(p => p.ProductID == id).FirstOrDefault(); if (currentProduct != null) { foreach(var item in productMockList) { if(item.ProductID.Equals(currentProduct.ProductID)) { item.ProductName = product.ProductName; item.Price = product.Price; item.Count = product.Count; item.Description = product.Description; } } } }
接着我們在Index View中添加修改Product代碼如下。
// Update product $('#btnSave').click(function () { var product = { ProductID: $('#txtProductID').val(), ProductName: $('#txtProductName').val(), Price: $('#txtPrice').val(), Count: $('#txtCount').val(), Description: $('#txtDescription').val() }; $.ajax({ url: '/api/products/' + $('#txtProductID').val(), type: 'POST', data: JSON.stringify(product), contentType: 'application/json' }).success(function (result) { LoadProductList(); $('#message').html("Product save success."); }).error(function (data) { alert(data); }); });
運行程序
加載Product列表,任意點擊一條數據的View鏈接,這里我們點擊第一條數據。

接着我們修改信息Product Name為"Product AAA",Count為10,Price為200000,Description為"Description AAA",並點擊Save按鈕。

5.刪除Product
這里我們像View Product一樣,在列表數據行中添加一個Delete鏈接。點擊Delete鏈接,刪除對應的Product數據。
首先我們先完成Web API中刪除Product數據的方法。
// DELETE api/products public void DeleteProduct(int id) { var product = productMockList.Where(p => p.ProductID == id).FirstOrDefault(); if (product != null) { productMockList.Remove(product); } }
接着修改Index View頁面,增加刪除功能。
// Display product list function DisplayProductList(result) { var productTable = $("<table cellpadding='5' cellspacing='5'></table>"); var productTableTitle = $("<tr style='background-color:#7FBA00;'><th>Product ID</th><th>Product Name</th><th>Price</th><th>Count</th><th>Description</th><th></th></tr>"); productTableTitle.appendTo(productTable); for (var i = 0; i < result.length; i++) { var productTableContent = $("<tr style='background-color: #7FBA00; color: white;'><td>" + result[i].ProductID + "</td><td>" + result[i].ProductName + "</td><td>" + result[i].Price + "</td><td>" + result[i].Count + "</td><td>" + result[i].Description + "</td>" + "<td><a href='#' onclick='ViewProduct(" + result[i].ProductID + ")'>View</a> <a href='#' onclick='DeleteProduct(" + result[i].ProductID + ")'>Delete</a></td></tr>"); productTableContent.appendTo(productTable); } $('#products').html(productTable); }
// Delete product function DeleteProduct(productID) { $.ajax({ url: '/api/products/' + productID, type: 'DELETE', }).success(function (result) { LoadProductList(); $('#message').html("Product delete success."); }).error(function (data) { alert(data); }) }
運行程序
加載列表

點擊Product A數據的Delete鏈接。

可以看到Product A的數據成功刪除。
好了,本篇就先到此,希望對你有所幫助,謝謝!
