HTML and CSS Reference
In-Depth Information
The MapHttpRoute() method maps the incoming requests to the Web API controller classes. For
example, a sample URL pointing to the Customer Web API controller is http://localhost:1050/api/
Customer .
Using XMLHttpRequest to Invoke the Web API
Now let's write the client-side jQuery code that invokes the Customer Web API controller using the
XMLHttpRequest object. The jQuery code primarily consists of four functions: GetCustomers() ,
InsertCustomer() , UpdateCustomer() , and DeleteCustomer() . These functions perform the respective
operations by calling a Web API method.
When the web form is loaded, it needs to display the Customer data; hence the GetCustomers()
function is called in the jQuery ready() function. Listing 11-9 shows how this is done. Some code has been
omitted for the sake of readability.
Listing 11-9. Creating an XMLHttpRequest Object and Displaying Data
$(document).ready(function () {
GetCustomers();
});
function GetCustomers() {
$(“#tblCustomers”).empty();
$(“#tblCustomers”).append(“<tr><th>…</tr>”);
var emptyRow = “<tr>”;
emptyRow += “<td><input size='5' type='text'/></td>”;
emptyRow += “<td><input type='button' value='Insert'/></td>”;
emptyRow += “</tr>”;
$(“#tblCustomers”).append(emptyRow);
var xhr = new XMLHttpRequest();
xhr.open(“GET”, “api/Customer”);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var data = JSON.parse(xhr.responseText);
for (var i = 0; i < data.length; i++) {
var row = “<tr>”;
row += “<td><input size='5' type='text' value='” + data[i].CustomerID +
“' readonly='readonly'/></td>”;
row += “<td><input type='button' value='Update'/>”;
row += “<input type='button' value='Delete'/></td>”;
row += “</tr>”;
$(“#tblCustomers”).append(row);
}
$(“#tblCustomers input[value='Insert']”).click(InsertCustomer);
$(“#tblCustomers input[value='Update']”).click(UpdateCustomer);
$(“#tblCustomers input[value='Delete']”).click(DeleteCustomer);
 
Search WWH ::




Custom Search