ASP.NET MVC4中調用WEB API的四個方法

來源:互聯網
上載者:User

使用jQuery 調用WEB API

接下來,我們在Index控制器中建立立一個視圖,如:

接下來就可以根據實際需要,決定在頁面中顯示customer表中的多少列,最後的頁面顯示如下:

當頁面載入時,使用GET()方法去調出customer表的所有資料,而當使用INSERT,UPDATE,DELETE功能時,是通過jQuery去調用web api的。下面我們學習下通過jQuery去調用WEB API。

首先,我們設計每一行的HTML代碼,如下:

<table id="customerTable" border="0" cellpadding="3">
<tr>
<th>Customer ID</th>
<th>Company Name</th>
<th>Contact Name</th>
<th>Country</th>
<th>Actions</th>
</tr>
<tr>
<td><input type="text" id="txtCustomerId" size="5"/></td>
<td><input type="text" id="txtCompanyName" /></td>
<td><input type="text" id="txtContactName" /></td>
<td><input type="text" id="txtCountry" /></td>
<td><input type="button" name="btnInsert" value="Insert" /></td>
</tr>
</table>

首先要引入jQuery類庫:

<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>

然後在jQuery中,通過$.getJSON的方法,調用WEB API,代碼如下:

$(document).ready(function () {

$.getJSON("api/customers", LoadCustomers);

});

熟悉jQuery的朋友肯定明白,$.getJson方法中第一個參數是調用服務的地址,第二個參數是回調方法,這個回調方法LoadCustomers中,將展示服務端web api返回的資料,代碼如下:

function LoadCustomers(data) {
    $("#customerTable").find("tr:gt(1)").remove();
    $.each(data, function (key, val) {
        var tableRow = '<tr>' +
'<td>' + val.CustomerID + '</td>' +
'<td><input type="text" value="' + val.CompanyName + '"/></td>' +
'<td><input type="text" value="' + val.ContactName + '"/></td>' +
'<td><input type="text" value="' + val.Country + '"/></td>' +
'<td><input type="button" name="btnUpdate" value="Update" />
<input type="button" name="btnDelete" value="Delete" /></td>' +
'</tr>';
        $('#customerTable').append(tableRow);
    });
    $("input[name='btnInsert']").click(OnInsert);
    $("input[name='btnUpdate']").click(OnUpdate);
    $("input[name='btnDelete']").click(OnDelete);
}

在上面的代碼中,首先移除所有表格中的行(除了表頭外),然後通過jQuery中的each方法,遍曆web api返回給前端的資料,最後展現所有的資料行。然後在Insert,update,delete三個按鈕中都綁定了相關的方法函數,下面先看update的代碼:

function OnUpdate(evt) {
    var cell;
    var customerId = $(this).parent().parent().children().get(0).innerHTML;
    cell = $(this).parent().parent().children().get(1);
    var companyName = $(cell).find('input').val();
    cell = $(this).parent().parent().children().get(2);
    var contactName = $(cell).find('input').val();
    cell = $(this).parent().parent().children().get(3);
    var country = $(cell).find('input').val();
    var data = '{"id":"' + customerId + '", "obj":{"CustomerID":"' + customerId +
'","CompanyName":"' + companyName + '","ContactName":"' +
               contactName + '","Country":"' + country + '"}}';
    $.ajax({
        type: 'PUT',
        url: '/api/customers/',
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (results) {
            $.getJSON("api/customers", LoadCustomers);
            alert('Customer Updated !');
        }
    })
}

在上面的代碼中,首先從每行的各個文字框中獲得要更新的值,然後組織成JSON資料,

其資料格式為包含兩項,其中一項包含customer的ID,另外一個是新的customer實體物件,因為WEB API的PUT方法需要的是兩個參數。

然後通過jQuery的$.ajax方法進行調用web api,注意這裡的type指定為put方法,並且注意編碼為UTF-8,然後在回調方法success中,再此使用$.getJSON方法,獲得更新後的最新使用者列表。

而Insert,Delete的方法代碼如下:

function OnInsert(evt) {
    var customerId = $("#txtCustomerId").val();
    var companyName = $("#txtCompanyName").val();
    var contactName = $("#txtContactName").val();
    var country = $("#txtCountry").val();
    var data = '{"obj":{"CustomerID":"' + customerId + '","CompanyName":"' + companyName +
'","ContactName":"' + contactName + '","Country":"' + country + '"}}';
    $.ajax({
        type: 'POST',
        url: '/api/customers/',
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (results) {
            $("#txtCustomerId").val('');
            $("#txtCompanyName").val('');
            $("#txtContactName").val('');
            $("#txtCountry").val('');
            $.getJSON("api/customers", LoadCustomers);
            alert('Customer Added !');
        }
    })
}
function OnDelete(evt) {
    var customerId = $(this).parent().parent().children().get(0).innerHTML;
    var data = '{"id":"' + customerId + '"}';
    var row = $(this).parent().parent();
    $.ajax({
        type: 'DELETE',
        url: '/api/customers/',
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (results) {
            $.getJSON("api/customers", LoadCustomers);
            alert('Customer Deleted!');
        }
    })
}

讀者要注意的是,在實際應用中,可以使用含有GET,PUT,DELETE首碼的方法名,比如

GetXXXX(), PutXXXX(), PostXXXX()都是可以的,XXX是自訂的名稱,WEB API架構依然會調用對應的GET,PUT和POST方法。

最後運行後,效果如:

 

 

 

網站開發_網站製作_網站維護_網店製作_網店安裝_商城製作_手機軟體_企業網站_辦公軟體_QQ:471226865
點點更健康

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.