Click here to Skip to main content
11,505,166 members (67,803 online)
Click here to Skip to main content

Implementing & Consuming ASP.NET WEB API from JQuery (MVC 4)

, 23 Jul 2012 CPOL 149.1K 40
Rate this:
Please Sign up or sign in to vote.
CodeProjectIn this post we will see how to create a our own WEB API service and will consume it in client using JQuery.This is the UI i am planning to create, which in-turn talk to a ASP.NET WEB API Service for rendering data. We need to create a API Service and an Application consuming it.Lets do i

In this post we will see how to create a our own WEB API service and will consume it in client using JQuery.

This is the UI i am planning to create, which in-turn talk to a ASP.NET WEB API Service for rendering data. We need to create a API Service and an Application consuming it.

Lets do it step by step.

Step 1: Create a solution and add 2 MVC 4 projects , one with WEB API template and another with INTERNET Application template.

Step 2: Lets create our custom WEB API Service. Go to API_SVC project and under Controllers folder you can see ValuesController.cs. This is the default WEB API service fie added, either you can modify, or you can add a new API Controller, using Add option.

 Step 3:I created a Service file with name "EmployeeAPI". EmployeeAPIConstroller.cs

namespace API_SVC.Controllers
{
    public class EmployeeAPIController : ApiController
    {
        private List<employee> EmpList = new List<employee>();
        public EmployeeAPIController()
        {
            EmpList.Add(new Employee(1, "Employee1", "Employee Department1", 9999888877));
            EmpList.Add(new Employee(2, "Employee2", "Employee Department2", 7777888899));
            EmpList.Add(new Employee(3, "Employee3", "Employee Department3", 9999777788));
        }
        // GET api/EmployeeAPI
        public IEnumerable<Employee> GetEmployees()
        {             
             return EmpList;   
        }

        // GET api/EmployeeAPI/5
        public Employee GetEmployee(int id)
        {
            return EmpList.Find(e => e.ID == id);
            
        }

        // POST api/EmployeeAPI
        public IEnumerable<Employee> Post(Employee value)
        {
            EmpList.Add(value);

            return EmpList;
        }

        // PUT api/EmployeeAPI/5
        public void Put(int id, string value)
        {

        }

        // DELETE api/EmployeeAPI/5
        public IEnumerable<Employee> Delete(int id)
        {
            EmpList.Remove(EmpList.Find(E => E.ID == id));
            return EmpList;
        }
    }
}</employee></employee>

Step 4:I ensure that it is hosted on IIS and can be accessed through URL mentioned on each of the service methods. for example lets check GetEmployee() method using Fiddler.

Action:

Result:

Now that we confirm that we are done with creation of simple WEB API HTTP Service.

Step 5:  Move to the second application i.e., API_APP , the MVC 4 internet application, and open Index.cshtml under Home. To demonstrate the simplicity of ASP.NET WEB API Service, i will call them using nothing but JQuery i.e., Client side code.  Index.cshtml Code View:

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>
                <h2>@ViewBag.Message</h2>
            </hgroup>
            <div>
                <table><tr>
                        <td><button onclick="GetAllEmployees();return false;">Get All Employees</button></td>
                        <td>Enter Employee Id: <input type="text" id="txtEmpid" style="width:50PX"/></td>
                        <td><button onclick="GetEmployee();return false;">Get Employee</button></td>
                    <td>
                        <table>
                            <tr><td>EmpId:</td><td><input type="text" id="txtaddEmpid" /></td></tr>
                            <tr>  <td>Emp Name:</td><td><input type="text" id="txtaddEmpName" /></td></tr>
                            <tr> <td>Emp Department:</td><td><input type="text" id="txtaddEmpDep" /></td></tr>
                            <tr><td>Mobile no:</td><td><input type="text" id="txtaddEmpMob" /></td></tr>
                        </table>
                    </td>
                        <td><button onclick="AddEmployee();return false;">Add Employee</button></td>
                    <td>Delete Employee <input type="text" id="txtdelEmpId" style="width:50PX"/></td>
                        <td><button onclick="DeleteEmployee(); return false;">Delete Employee</button></td>
                       </tr></table>
                
            </div>
        </div>
    </section>
}
<h3>Oputput of action done through WEB API:</h3>
<ol class="round">
    <li>
        <div id="divResult"></div>

    </li>
</ol>

Index.cshtml UI view

Step 6: Lets see how we can associate each button to an action of API Service. First look at "Get All Employees" button and its onclick event in above code.Its is calling "GetAllEmployees()" , a script function in-turn calling WEB API Service using JQuery.

function GetAllEmployees() {
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI',
            type: 'GET',
            dataType: 'json',            
            success: function (data) {                
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });        
    }

Spare sometime looking at above code snippet. See the URL part of Ajax Get request, that is all we need to consume the WEB API Service we created earlier. Make sure you give all the parameters properly so that it invoke right methods.

Step 7:  WriteResponse() and ShowEmployee() are the 2 methods i created to display the JSON result in a proper way. Below is the JQuery part associating each button to a method of WEB API Service.

<script type="text/javascript">
    function GetAllEmployees() {
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI',
            type: 'GET',
            dataType: 'json',            
            success: function (data) {                
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });        
    }

    function AddEmployee() {
        jQuery.support.cors = true;
        var employee = {
            ID: $('#txtaddEmpid').val(),
            EmpName: $('#txtaddEmpName').val(),
            EmpDepartment: $('#txtaddEmpDep').val(),
            EmpMobile: $('#txtaddEmpMob').val()
        };       
        
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI',
            type: 'POST',
            data:JSON.stringify(employee),            
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }

    function DeleteEmployee() {
        jQuery.support.cors = true;
        var id = $('#txtdelEmpId').val()       
        
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI/'+id,
            type: 'DELETE',            
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                WriteResponse(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }

    function WriteResponse(employees) {        
        var strResult = "<table><th>EmpID</th><th>Emp Name</th><th>Emp Department</th><th>Mobile No</th>";        
        $.each(employees, function (index, employee) {                        
            strResult += "<tr><td>" + employee.ID + "</td><td> " + employee.EmpName + "</td><td>" + employee.EmpDepartment + "</td><td>" + employee.EmpMobile + "</td></tr>";
        });
        strResult += "</table>";
        $("#divResult").html(strResult);
    }

    function ShowEmployee(employee) {
        if (employee != null) {
            var strResult = "<table><th>EmpID</th><th>Emp Name</th><th>Emp Department</th><th>Mobile No</th>";
            strResult += "<tr><td>" + employee.ID + "</td><td> " + employee.EmpName + "</td><td>" + employee.EmpDepartment + "</td><td>" + employee.EmpMobile + "</td></tr>";
            strResult += "</table>";
            $("#divResult").html(strResult);
        }
        else {
            $("#divResult").html("No Results To Display");
        }
    }
   
    function GetEmployee() {
        jQuery.support.cors = true;
        var id = $('#txtEmpid').val();        
        $.ajax({
            url: 'http://localhost:8080/API_SVC/api/EmployeeAPI/'+id,
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                ShowEmployee(data);
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    }
</script>

Step 8: What else we left with except verifying the output.

Action 1:

Action 2:

Action 3:

Action 4:

Step 9: Apart from fact that it is simple to configure and create, we need to consider that its a RESTful service which is light weight and will have  incredible performance.

Look at the below snapshot of HttpWatch Log for Action #1, which was completed in 50 milli seconds. I accept both applications are on same machine and solution, but the communication never happened through dlls. The execution happened via IIS just like typical service call. Even if you add the Network lag, we should say it is a good performance.

With this we have seen how to create and consume our own ASP.NET WEB API Service, even with out adding a single line of Server code on client application. Can any service configuration be simpler than this? Is it helpful for you? Kindly let me know your comments / Questions.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
GeneralMy vote of 5 Pin
WesMcGJr12-Mar-15 2:35
memberWesMcGJr12-Mar-15 2:35 
Questiongood article , will use it a lot Pin
Member 114907751-Mar-15 22:16
memberMember 114907751-Mar-15 22:16 
Questionhow to use with db ? Pin
woot_woot29-Dec-14 8:06
memberwoot_woot29-Dec-14 8:06 
GeneralMy vote of 4 Pin
Member 1025294022-Dec-14 17:16
memberMember 1025294022-Dec-14 17:16 
QuestionGood Article Pin
Member 8053122-Dec-14 7:12
memberMember 8053122-Dec-14 7:12 
QuestionGreat Post!! Pin
Member 1086450823-Sep-14 3:37
memberMember 1086450823-Sep-14 3:37 
QuestionThis article is a joke Pin
Member 1106958912-Sep-14 3:50
memberMember 1106958912-Sep-14 3:50 
QuestionRe: This article is a joke Pin
Ravi Bhavnani12-Sep-14 4:17
professionalRavi Bhavnani12-Sep-14 4:17 
QuestionSource Code of index.cshtml file required. Pin
Member 1106958910-Sep-14 5:21
memberMember 1106958910-Sep-14 5:21 
Question[object Object] Error not Found Pin
Ahormazda12-Aug-14 18:09
memberAhormazda12-Aug-14 18:09 
GeneralSource Code Pin
GurmailSingh30-Jul-14 1:41
memberGurmailSingh30-Jul-14 1:41 
QuestionSource Code Pin
ameur_ca12-Jul-14 8:10
memberameur_ca12-Jul-14 8:10 
QuestionWhy every time when i'm updating it dosent save the list? [modified] Pin
Member 106420214-Mar-14 1:18
memberMember 106420214-Mar-14 1:18 
AnswerRe: Why every time when i'm updating it dosent save the list? Pin
PratapReddyP6-Mar-14 14:02
memberPratapReddyP6-Mar-14 14:02 
GeneralSecurity Pin
vahid.mo31-Jan-14 8:12
membervahid.mo31-Jan-14 8:12 
Bug[My vote of 1] This Article, will be usefull, but at this moment it's only an incomplete and buggy howto since date of creation. Pin
Ivan Dorna6-Jan-14 22:57
memberIvan Dorna6-Jan-14 22:57 
QuestionCORS compatibility? Pin
venkatesun29-Dec-13 22:42
membervenkatesun29-Dec-13 22:42 
QuestionSource code Pin
Mayuresh8018-Dec-13 4:44
memberMayuresh8018-Dec-13 4:44 
QuestionThanks! Pin
ADumbDeveloper14-Nov-13 5:17
memberADumbDeveloper14-Nov-13 5:17 
GeneralMy vote of 5 Pin
tailton7-Jul-13 1:39
membertailton7-Jul-13 1:39 
GeneralMy vote of 4 Pin
leomultimedia9-Jun-13 6:08
memberleomultimedia9-Jun-13 6:08 
GeneralRegarding Pin
sameer_s1-May-13 2:03
membersameer_s1-May-13 2:03 
GeneralThanks for this concise and to the point article Pin
R1239891-May-13 0:21
memberR1239891-May-13 0:21 
GeneralMy vote of 4 Pin
R1239891-May-13 0:19
memberR1239891-May-13 0:19 
GeneralThanks for this sample! Pin
netfile29-Mar-13 10:05
membernetfile29-Mar-13 10:05 
Questionweb api quetion Pin
vaibhavijoshi24-Mar-13 19:08
membervaibhavijoshi24-Mar-13 19:08 
QuestionSample code Pin
Duduman Bogdan Vlad30-Jan-13 3:27
memberDuduman Bogdan Vlad30-Jan-13 3:27 
GeneralRegarding availability of source code. Pin
gskalra21-Jan-13 22:19
membergskalra21-Jan-13 22:19 
QuestionProblem with cross domain Pin
mahdsoft21-Oct-12 0:20
membermahdsoft21-Oct-12 0:20 
AnswerRe: Problem with cross domain Pin
PratapReddyP28-Oct-12 7:36
memberPratapReddyP28-Oct-12 7:36 
AnswerRe: Problem with cross domain Pin
Chris Pels25-Feb-13 8:02
memberChris Pels25-Feb-13 8:02 
GeneralRe: Problem with cross domain Pin
PratapReddyP25-Feb-13 9:12
memberPratapReddyP25-Feb-13 9:12 
AnswerRe: Problem with cross domain Pin
Pratik Bhuva22-Oct-13 4:24
memberPratik Bhuva22-Oct-13 4:24 
QuestionThank Pin
thanhtranh2824-Sep-12 21:47
memberthanhtranh2824-Sep-12 21:47 
QuestionEmployee object? Pin
Edward DeGagne10-Sep-12 4:42
memberEdward DeGagne10-Sep-12 4:42 
AnswerRe: Employee object? Pin
Bobby Montalvo17-Jan-13 9:00
memberBobby Montalvo17-Jan-13 9:00 
GeneralRe: Employee object? Pin
Member 165621424-Oct-13 7:48
memberMember 165621424-Oct-13 7:48 
QuestionUpdate the list Pin
Eugene Popov22-Jul-12 9:18
memberEugene Popov22-Jul-12 9:18 
AnswerRe: Update the list Pin
PratapReddyP22-Jul-12 16:27
memberPratapReddyP22-Jul-12 16:27 
QuestionThank u! Pin
congdungiq20-Jul-12 16:27
membercongdungiq20-Jul-12 16:27 
AnswerRe: Thank u! Pin
PratapReddyP22-Jul-12 2:11
memberPratapReddyP22-Jul-12 2:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 23 Jul 2012
Article Copyright 2012 by PratapReddyP
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid