Srikanth Technologies

Contacts Web API and jQuery Client

This blog shows how to create a Web API to perform create (insert), delete, update and read operations using Entity Framework for data access.

The client for this Web API is a simple HTML page with jQuery making Ajax requests to Web API.

The focus of the blog is on Web API and how to send GET, POST, DELETE and PUT requests using Ajax with jQuery.

Classes related to Entity Framework

First make sure you have created required metadata related to Entity Framework to access CONTACT tables in Sql Server database.

Entity Framework creates the following two classes (Contact and ContactsContext) that are used in Web API along with metadata.

  public partial class Contact
 {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Mobile { get; set; }
 }
  public partial class ContactsContext : DbContext
 {
        public ContactsContext()
            : base("name=msdbEntities")  // msdbEntities is connectionstring in web.config
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public DbSet<Contact> Contacts { get; set; }
 }

ContactsController.cs

This is Web API that handles GET, POST, DELETE and PUT requests coming from client.

using restdemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace restdemo.Controllers
{
    public class ContactsController : ApiController
    {
        public void Post(Contact contact)
        {
            try
            {
                ContactsContext ctx = new ContactsContext();
                ctx.Contacts.Add(contact);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                HttpResponseMessage msg = new HttpResponseMessage();
                msg.StatusCode = HttpStatusCode.InternalServerError;
                msg.ReasonPhrase = "Error while adding contact -> " + ex.Message;
                throw new HttpResponseException(msg); 
            }
        }

        // GET api/Contacts
        public List<restdemo.Models.Contact> Get()
        {
            ContactsContext ctx = new ContactsContext();
            return ctx.Contacts.ToList<Contact>();
        }

        // GET api/Contacts/id
        public Contact Get(String id)
        {
            ContactsContext ctx = new ContactsContext();
            var contact = (from c in ctx.Contacts
                           where c.Name.ToUpper() == id.ToUpper()
                           select c).SingleOrDefault();
            return contact; 
        }


        // DELETE api/Contacts/id
        public void Delete(String id)
        {
            ContactsContext ctx = new ContactsContext();
            var contact = (from c in ctx.Contacts
                           where c.Name.ToUpper() == id.ToUpper()
                           select c).SingleOrDefault();
            if (contact != null)
            {
                ctx.Contacts.Remove(contact);
                ctx.SaveChanges();
            }
            else
                throw new Exception("Contact Not Found");
        }

        // PUT api/Contacts/id
        public void Put(String id, Contact newContact)
        {
            ContactsContext ctx = new ContactsContext();
            var contact = (from c in ctx.Contacts
                           where c.Name.ToUpper() == id.ToUpper()
                           select c).SingleOrDefault();
            contact.Email = newContact.Email;
            contact.Mobile = newContact.Mobile;
            ctx.SaveChanges();
        }
    }
}


ContactsClient.html

This HTML page uses jQuery to make Ajax request to Web API for different operations.

This client assumes Web API is running at port 55943. Feel free to change this port number according to your case.


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.7.1.min.js"></script>
    <style>
        body {
            font-family: Verdana;
            font-size: 12pt;
        }
        h2 {
            color :red;
        }
        td {
            text-align :center;
        }
        .button  {
            color:white;
            background-color: gray;
            font-size:12pt;
            width:100px;
        }
    </style>
    <script type="text/javascript">
        function GetInfo() {
            var url = "http://localhost:55943/api/Contacts/" + $("#txtName").val();
            $.getJSON(url, {}, showInfo);
        }
        function showInfo(data) {
            $("#error").html("");
            if (data) {
                $("#txtEmail").val(data.Email);
                $("#txtMobile").val(data.Mobile);
            }
            else
                $("#error").html("Sorry! Name not found");
        }

        function DeleteContact() {
            var url = "http://localhost:55943/api/Contacts/" + $("#txtName").val();
            $.ajax({ "url" : url, "type" : "delete",  "success" : deleted });
        }

        function deleted() {
            GetContacts();
            ClearFields();
        }


        function GetContacts() {
            var url = "http://localhost:55943/api/Contacts";
            $.getJSON(url, {}, showAll);
        }
        function showAll(contacts) {
            var out = "<table width='100%' border='1' cellpadding='5pt'> <tr style='background-color:navy;color:white'><th>Name</th><th>Email </th><th>Mobile </th></tr>";
            $.each(contacts,
                function (index, contact) {
                    out = out + "<tr><td>" + contact.Name + "</td><td>" + contact.Email +
                           "</td><td>" + contact.Mobile + "</td></tr>";
                }
            );

            out = out + "</table>";
            $("#output").html(out);
        }

        function AddContact() {
            var url = "http://localhost:55943/api/Contacts";
            var data = {
                "name": $("#txtName").val(),
                "email": $("#txtEmail").val(),
                "mobile": $("#txtMobile").val()
            };

            $.ajax({ "url": url,  "data" : data,  "type": "post",  "success" : added , "error" : displayError });
        }

        function displayError(xhr, status, error) {
            alert("Sorry! Could not complete task due to error!" + error);
        }

        function added() {
            GetContacts();
            ClearFields();
        }

        function UpdateContact() {
            var url = "http://localhost:55943/api/Contacts/" + $("#txtName").val() ;
            var data = {
                "email": $("#txtEmail").val(),
                "mobile": $("#txtMobile").val()
            };

            $.ajax({ "url": url, "data": data, "type" : "put", "success" : updated, "error" : displayError });
        }

        function updated() {
            GetContacts();
           
        }

        function ClearFields() {
            $("#txtName").val("");
            $("#txtEmail").val("");
            $("#txtMobile").val("");
        }

        // document ready 
        $(function () {
            GetContacts();
          }
        );

    </script>
</head>
<body>

    <h2>Contacts Manager</h2>
    Contact Name : 
    <br />
    <input type="text" id="txtName" required="required" />
    <input type="button" value="Get Details" onclick="GetInfo()" class="button" />
    <span id="error"></span>
    <p />
    Email Address : 
    <br />
    <input type="email" id="txtEmail" />
    <p />
    Mobile Number :
    <br />
    <input type="text" id="txtMobile" />
    <p />
    <input type="button" value="Delete" onclick="DeleteContact()"  class="button"/>
    <input type="button" value="Update" onclick="UpdateContact()" class="button" />
    <input type="button" value="Add"  onclick="AddContact()" class="button"/>
    <p />
    
    <fieldset>
         <legend>Contacts</legend>
         <div id="output"></div>
    </fieldset>
     

</body>
</html>