其它的前面都说过了,我们再来看一下最后两个方法Put Delete
前台代码:
1 @{ 2 //Layout = null; 3 } 4 5 <!DOCTYPE html> 6 <html> 7 <head> 8 <meta name="viewport" content="width=device-width" /> 9 <title></title> 10 <script src="~/Scripts/jquery-1.10.2.min.js"></script> 11 <script> 12 var url = "http://" + window.location.host + "/api/ProductsAPI"; 13 function submitbtn() { 14 $.ajax({ 15 url: url + "/GetAllProducts", 16 type: "GET", 17 dataType: "json", 18 success: function (data) { 19 var arr = ["<ul>"]; 20 for (var i = 0; i < data.length; i++) { 21 arr.push("<li>id=" + data[i].Id + " name = " + data[i].Name + " Category = " + data[i].Category + " Price = " + data[i].Price + "</li>") 22 } 23 arr.push("</ul>"); 24 $("#div1").html(arr.join('')); 25 } 26 }); 27 } 28 function submitbtn2() { 29 $.ajax({ 30 url: url + "/PostProduct", 31 type: "post", 32 data: 33 { 34 id: 100, 35 name: "b", 36 Category: "b", 37 Price: 11 38 }, 39 success: function (data) { 40 submitbtn(); 41 } 42 }); 43 } 44 function DeleteProduct() { 45 var id = $("input[name='id']").val(); 46 $.ajax({ 47 url: url + "/DeleteProduct/" + id, 48 type: "Delete", success: function (data) { 49 submitbtn(); 50 } 51 }); 52 } 53 54 function PutProduct() { 55 var id = $("input[name='id']").val(); 56 $.ajax({ 57 url: url + "/PutProduct/" + id, 58 type: "put", 59 data: { 60 Id: id, 61 name: "修改的值", 62 Category: "修改的值", 63 Price: 111 64 }, 65 success: function (data) { 66 submitbtn(); 67 } 68 }); 69 } 70 </script> 71 </head> 72 <body> 73 <div> 74 <div id="div1"></div> 75 <input type="button" value="查询所有数据 get" onclick="submitbtn()" /> 76 <br /> 77 <input type="button" value="增加一个name为B的数据 post" onclick="submitbtn2()" /> 78 <br /> 79 <input name="id" type="number" value="1" /> 80 <input type="button" value="删除一个数据 Delete" onclick="DeleteProduct()" /> 81 82 <input type="button" value="修改一个数据 put" onclick="PutProduct()" /> 83 </div> 84 </body> 85 </html>
后台代码就直接少写一点了:
1 public IHttpActionResult PutProduct(int id, Product product) 2 { 3 product.Id = id; 4 if (repository.Update(product)) 5 { 6 return StatusCode(HttpStatusCode.NoContent); 7 } 8 return NotFound(); 9 } 10 public HttpResponseMessage DeleteProduct(int id) 11 { 12 repository.Remove(id); 13 return new HttpResponseMessage(HttpStatusCode.NoContent); 14 }
get和post不需要写返回状态,因为webapi默认get和post协议返回200。
但put和delete就需要返回204了,以上的写法是强化协议的状态。
PS:Put 和Delete方法可以直接写成void无返回值,webapi自动返回204。但如果失败前端又只能得到服务器处理成功的结果,最好的方法,还是处理一下。
本文为博主原创文章,欢迎转载,但转载须注在明显位置注明【博客地址】和【原文地址】,否则将追究法律责任。http://www.cnblogs.com/cxd1008