|
In one of the previous article Consuming Web API using jQuery and inspecting Request and Response I talked about how to consume Web API to retrieves data in web page. In this article I will talk about how to Save, Update or Delete data using Web API from web page.
Let's write code.
Step 1: Download code from Consuming Web API using jQuery and inspecting Request and Response or you can create Web API application following the steps present in the article.
Step 2: Open CustromerController.cs present in Controller folder and two methods one to Delete Customer other to Save or Update Customer.
DelterCustomer will get the customerId and one can delete the respective customer
public Customer DeleteCustomer(int customerId) { //Code to delete customer return new Customer { CustomerId = 100, CustomerName = "Hemant", Address = "Bangalore" }; }
PostCustomer will take customer object and update or save customer.
public Customer PostCustomer(Customer customer) { //Code to save or update customer return customer; }
Step 3: Add Delete and Update/Save button in DemoWebAPI.Html. On click of DeleteCustomer DeleteCustomer method will be invoked and on click of Update/Save Customer UpdateORSaveCustomer method will be invoked.
<input type="button" value="Delete Customer" onclick="DeleteCustomer();" /> <br /> <input type="button" value="Update/Save Customer" onclick="UpdateORSaveCustomer();" /> <p id="customers" />
Step 4: Download json2. json2 will be used to stringify the object.
Step 5: Add json2.js in the Scripts folder.

Step 6: Add reference of json2.js in the DemoWebAPI.Html.
< script src="Scripts/json2.js" type="text/javascript"></script>
Step 7: Add below method which will update or save customer.
function UpdateORSaveCustomer() { var customer = { CustomerId: "CId", CustomerName: "CName", Address: "CAddress" };
var jsondata = JSON.stringify(customer);
$.ajax({ url: "/api/customer/", type: 'POST', data: jsondata, contentType: 'application/json; charset=utf-8', cache: false, statusCode: { 200: function (data) { alert('Data saved or updated successfully.'); } } }); }
Step 8: Now navigate to DemoWebAPI.Html. Press F12 and run developer tool. Go to Network tab and click on "Start Capturing".
Now click on Update/Save Customer button. You will notice below request.

Request Body tabe will contain the json request.

Step 9: Now, add below method which will be invoked on click of Delete Customer button. For delete type should be specified as DELETE.
function DeleteCustomer() { $.ajax({ url: "/api/customer/?customerid=" + 1, type: 'DELETE', cache: false, statusCode: { 200: function (data) { alert('Data deleted successfully.'); } } }); }
Step 10: Now navigate to DemoWebAPI.Html. Press F12 and run developer tool. Go to Network tab and click on "Start Capturing".
Now click on Delete Customer button. You will notice below request.

This ends the article of Save, Update or Delete using Web API from web page.
|