昨天《怎样操作WebAPI接口(显示数据)》http://www.cnblogs.com/insus/p/5670401.html
既有使用jQuery,也有使作HttpClient来从数据库获取数据,并显示在ASP.NET MVC的视图中。
今天Insus.NET想把例子全完成,就是把其余的添加,更新,删除功能对Web API进行POST,PUT和DELETE操作。
去控制器创建3个操作,即所谓的Action,它们分别是POST(添加),PUT(更新),DELETE(删除):
纵观访问Web API,如果API的方法是命名用默认的方法名的话,所有连接地址均一样。
PostDataToApi.cshtml视图:
$(function () { $("#Button1").on("click", function () { var obj = {}; obj.SizeName = $("#Text1").val(); $.ajax({ type: "POST", url: "http://localhost:9001/api/size", dataType: "json", contentType: "application/json; charset=utf-8", data: JSON.stringify(obj), success: function (data) { alert("数据成功添加!"); }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); } }); }); });
$(function () { $('table').on('click', '#Button1', function () { var row = $(this).closest('tr'), cells = row.find('td'); var obj = {}; obj.Size_nbr = cells.find("input:hidden[id=Hidden1]").val() obj.SizeName = cells.find("input[id='Text1']").val(); $.ajax({ type: "PUT", url: "http://localhost:9001/api/size", data: JSON.stringify(obj), dataType: "json", contentType: "application/json; charset=utf-8", success: function (data) { alert("Update successfully!") $(location).attr('href', "PutDataApi"); }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); } }); }); });
$(function () { $('table').on('click', '#Button1', function () { var row = $(this).closest('tr'), cells = row.find('td'); var obj = {}; obj.Size_nbr = cells.find("input:hidden[id=Hidden1]").val() $.ajax({ type: "Delete", url: "http://localhost:9001/api/size", data: JSON.stringify(obj), dataType: "json", contentType: "application/json; charset=utf-8", success: function (data) { alert("Delete successfully!") row.remove(); }, error: function (jqXHR, textStatus, errorThrown) { alert(errorThrown); } }); }); });