ASP.NET Web API 基本操作(CRUD)
上一篇介紹了ASP.NET Web API的基本知識(shí)和原理,這一篇我們通過(guò)一個(gè)更直觀的實(shí)例,對(duì)產(chǎn)品進(jìn)行CRUD操作(Create/Read/Update/Delete)來(lái)繼續(xù)了解一下它的基本應(yīng)用。
?
創(chuàng)建ASP.NET Web API應(yīng)用程序?
在VS中選擇創(chuàng)建一個(gè)ASP.NET Web Application應(yīng)用程序,在向?qū)У南乱粋€(gè)窗口中選擇Web API模板。
?
創(chuàng)建Model
這里我們?cè)?strong>Models文件夾下創(chuàng)建一個(gè)簡(jiǎn)單的Product model類,用來(lái)傳遞數(shù)據(jù)。
在Models文件夾上點(diǎn)擊右鍵,選擇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; }}
創(chuàng)建Controller
接著在Controllers文件夾下創(chuàng)建一個(gè)API Controller, 命名為"ProductsController"。
在Controllers文件夾上點(diǎn)擊右鍵,選擇Add -> Controller ,在彈出向?qū)е羞x擇Web API 2 Controller - Empty
在向?qū)乱徊街休斎?strong>API Controller name為"ProductsController"。
?
創(chuàng)建Web API方法(CRUD)并通過(guò)JQuery和Ajax進(jìn)行數(shù)據(jù)操作
1.獲取Product列表
首先打開(kāi)ProductsController文件,添加模擬數(shù)據(jù)以及獲取Product列表的方法。
?
public class ProductsController : ApiController{// Mock product liststatic 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/productspublic IEnumerable<Product> GetAllProducts(){return productMockList;}}接著在文件夾Views->Product下創(chuàng)建一個(gè)View,名為"Index"。這里我們需要實(shí)現(xiàn)的是點(diǎn)擊Get Product List按鈕獲取Product List數(shù)據(jù),修改代碼如下:
@{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>運(yùn)行代碼,點(diǎn)擊Get Product List按鈕之前。
點(diǎn)擊Get Product List按鈕之后
2.獲取一條Product數(shù)據(jù)
這里我們的做法是點(diǎn)擊列表右側(cè)View鏈接,獲取當(dāng)前Product數(shù)據(jù),并顯示到列表下方各個(gè)字段對(duì)應(yīng)的文本框中。
首先我們先完成Web API中獲取一條Product數(shù)據(jù)的方法。
// GET api/products/?public Product GetProdcut(int id){return productMockList.Where(p => p.ProductID == id).FirstOrDefault();}接著,在Product列表中添加一列View,在列表下面添加對(duì)應(yīng)各個(gè)字段的textbox。實(shí)現(xiàn)點(diǎn)擊View鏈接,獲取當(dāng)前Product數(shù)據(jù),然后顯示到對(duì)應(yīng)的文本框中。
@{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='#' οnclick='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>運(yùn)行程序
點(diǎn)擊Get Product List按鈕獲取列表數(shù)據(jù),顯示如下。
接著點(diǎn)擊列表中任意記錄右邊的View鏈接,這里我們點(diǎn)擊第一條數(shù)據(jù)View鏈接,顯示如下。
3.新增一條Product
這里我們需要一個(gè)Create Product的按鈕,然后利用上面創(chuàng)建的TextBox來(lái)實(shí)現(xiàn)新增數(shù)據(jù)功能。
首先我們先完成Web API中新增Product數(shù)據(jù)的方法。
// POST api/productspublic 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頁(yè)面實(shí)現(xiàn)新增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='#' οnclick='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>運(yùn)行程序
點(diǎn)擊獲取列表
點(diǎn)擊Create Product按鈕,輸入新增的Product數(shù)據(jù)。
點(diǎn)擊Create按鈕,結(jié)果如下圖。
4.修改Product信息
我們這里要實(shí)現(xiàn)的是點(diǎn)擊列表數(shù)據(jù)中的View鏈接,在文本框中修改選擇的Product信息,然后點(diǎn)擊Save按鈕,數(shù)據(jù)修改成功。
首先我們先完成Web API中修改Product數(shù)據(jù)的方法。
// PUT api/productspublic 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;}}}}接著我們?cè)?strong>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);});});運(yùn)行程序
加載Product列表,任意點(diǎn)擊一條數(shù)據(jù)的View鏈接,這里我們點(diǎn)擊第一條數(shù)據(jù)。
接著我們修改信息Product Name為"Product AAA",Count為10,Price為200000,Description為"Description AAA",并點(diǎn)擊Save按鈕。
5.刪除Product
這里我們像View Product一樣,在列表數(shù)據(jù)行中添加一個(gè)Delete鏈接。點(diǎn)擊Delete鏈接,刪除對(duì)應(yīng)的Product數(shù)據(jù)。
首先我們先完成Web API中刪除Product數(shù)據(jù)的方法。
// DELETE api/productspublic void DeleteProduct(int id){var product = productMockList.Where(p => p.ProductID == id).FirstOrDefault();if (product != null){productMockList.Remove(product);}}接著修改Index View頁(yè)面,增加刪除功能。
// 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='#' οnclick='ViewProduct(" + result[i].ProductID + ")'>View</a> <a href='#' οnclick='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);})}運(yùn)行程序
加載列表
點(diǎn)擊Product A數(shù)據(jù)的Delete鏈接。
可以看到Product A的數(shù)據(jù)成功刪除。
?
?
好了,本篇就先到此,希望對(duì)你有所幫助,謝謝!
?
轉(zhuǎn)載于:https://www.cnblogs.com/mejoy/p/6408735.html
總結(jié)
以上是生活随笔為你收集整理的ASP.NET Web API 基本操作(CRUD)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

- 上一篇: HDU-3743 Minimum Sum
- 下一篇: 樱花飞舞