Four Methods for calling WEB APIs in ASP. NET MVC4

Source: Internet
Author: User
Tags custom name

Use jQuery to call WEB APIs

Next, we create a new view in the Index controller, for example:

Next, you can determine the number of columns in the customer table on the page according to your actual needs. The final page is shown as follows:

When a page is loaded, the GET () method is used to call all data in the customer table. When the INSERT, UPDATE, and DELETE functions are used, jQuery is used to call the web api. Next we will learn how to use jQuery to call WEB APIs.

First, we design the HTML code for each line as follows:

<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>

First introduce the jQuery Class Library:

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

In jQuery, call the web api through the $. getJSON method. The Code is as follows:

$ (Document). ready (function (){

$. GetJSON ("api/Mers MERs", LoadCustomers );

});

Anyone familiar with jQuery must understand, $. in the getJson method, the first parameter is the address of the service to be called, and the second parameter is the callback method. In the callback method LoadCustomers, the data returned by the server web api is displayed. The Code is as follows:

Function LoadCustomers (data ){
$ ("# CustomerTable"). find ("tr: gt (1)"). remove ();
$. Each (data, function (key, val ){
Var tableRow = '<tr>' +
'<Td>' + val. mermerid + '</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> ';
$ ('# Mermertable'). append (tableRow );
});
$ ("Input [name = 'btninsert']"). click (OnInsert );
$ ("Input [name = 'btnupdate']"). click (OnUpdate );
$ ("Input [name = 'btndelete']"). click (OnDelete );
}

In the code above, first remove all rows in the table (except the header), then use the each method in jQuery to traverse the data returned to the front-end by the web api, and finally display all data rows. Then, related method functions are bound to the Insert, update, and delete buttons. The update code is as follows:

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/Mers MERs /',
Data: data,
ContentType: "application/json; charset = UTF-8 ",
DataType: 'json ',
Success: function (results ){
$. GetJSON ("api/Mers MERs", LoadCustomers );
Alert ('customer Updated! ');
}
})
}

In the above Code, first obtain the value to be updated from each text box in each line, and then organize it into JSON data,

The data format includes two items, one of which includes the customer ID and the other is the new customer entity object, because the PUT Method of web api requires two parameters.

Then use the $. ajax method to call the web api, note that the type here is specified as the put method, and pay attention to Encoding As the UTF-8, and then in the callback method success, then use $. getJSON method to obtain the latest user list after update.

The code for the Insert and Delete methods is as follows:

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/Mers MERs /',
Data: data,
ContentType: "application/json; charset = UTF-8 ",
DataType: 'json ',
Success: function (results ){
$ ("# TxtCustomerId"). val ('');
$ ("# TxtCompanyName"). val ('');
$ ("# TxtContactName"). val ('');
$ ("# TxtCountry"). val ('');
$. GetJSON ("api/Mers MERs", 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/Mers MERs /',
Data: data,
ContentType: "application/json; charset = UTF-8 ",
DataType: 'json ',
Success: function (results ){
$. GetJSON ("api/Mers MERs", LoadCustomers );
Alert ('customer Deleted! ');
}
})
}

In practice, you can use method names that contain the GET, PUT, and DELETE prefixes, such

GetXXXX (), PutXXXX (), and PostXXXX () are all supported. XXX is a custom name. The web api framework still calls the corresponding GET, PUT, and POST methods.

After the final operation, the effect is as follows:

 

 

 

Website development _ website production _ website maintenance _ online shop production _ online shop installation _ mall production _ mobile phone software _ enterprise website _ office software _ QQ: 471226865
Point more healthy

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.