JQuery AJAX CRUD Operation On Web API - Part II

Aug 24, 2013
Download Source

In previous post we created a simple Contacts management API, and a jQuery AJAX operation to invoke Get operation on the API. In this post we will continue working with the same sample and implement remaining three operations PUT/POST/DELETE.

jQuery Function To Perform POST Operation

This function will help us crate a new contact entity using JavaScript client. For this, let's first create some HTML elements where we can enter new contact details.

Add File

The button is invoking a JavaScript function, which essential is our next jQuey AJAX call to our Web API's POST ActionMethod.

Add File

Let's also quickly understand what this code does. First we collect all the values from the input boxes and construct the Contact object. Next we will make Ajax call to our Web API with type set to POST.

Go ahead and click on the Get All Contacts button and we should see the newly added Contact in to the previous list.

Add File

jQuery Function To Perform PUT Operation

Next, let's write our next JavaScript function to perform PUT operation on our Web API. This is basically going to be an Update operation of an existing Contact. Let's create UI elements For this operation. Go ahead and create following HTML Elements.

Edit HTML elements

That should generate user interface similar to following screen.

Edit Screen

Both the buttons are invoke are invoking JavaScript functions which are displayed below.

Edit Screen

This function is almost similar to our GetAllContacts function except the fact that it now needs to load only single contact that we want to edit as oppose to bringing everything. That's why you will see minor difference (Highlighted in Red) in the URL, where we are going to make the AJAX call.

Next function is actually going to read all the values form the Edit input boxes and make a PUT request to our API.

Edit Screen

This function is also the same as POST AJAX call except the highlighted differences. The main difference being the request type being converted to PUT instead of POST.

With these in place, let's go ahead a pull record for Edit.

Edit Contact

Updated the values of the contact and click "Update Contact"button. Once you see the success message, go ahead and pull all the contacts for viewing and you should see the contact updated

Edit Contact

And that's it. Now we have basic Asp .Net Web API running in an Asp .Net MVC shell application. And the same application's view is consuming the API using AJAX operations.This concludes my 3 part series on Asp .Net Web API.

I hope this was helpful for Web API beginners and you guys enjoyed it.