ASP.NET Web API Using MVC, Entity Framework And jQuery For Retrieve Data - Part Two

Introduction

 
ASP.NET Web API is a framework for building Web API’s, i.e. HTTP based services on top of the .NET Framework. The most common use case for using a Web API is for building RESTful services.
 
Description
 
In this application I will show you the steps to get data from a Web api using Jquery. Before going through this session visit my Part One session.
Way To Source Code
Important steps to be followed for the previous session.
 
Create New Project for WebApi
 
Go to File > New > Project > Select asp.net MVC web application > Entry Application Name > Click OK > Select Web API > Select view engine Razor > OK
 
Add a new Api Controller.
 
Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty API Controller"> Add.
 
Add Application_BeginRequest event in the Global.asax.cs file for allow Cross-origin resource sharing.
  1. protected void Application_BeginRequest()  
  2.         {  
  3.             string[] allowedOrigin = new string[] { "http://localhost:12477" };  
  4.             var origin = HttpContext.Current.Request.Headers["Origin"];  
  5.             if (origin != null && allowedOrigin.Contains(origin))  
  6.             {  
  7.                 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origin);  
  8.                 HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods""GET,POST");  
  9.             }  
  10.         } 
Here I will write code for "Allow Origin" which will  allow the client application to consume the application services, which allows cross domain ajax calls. CORS support was released with ASP.NET Web API 2.T o provide support for CORS in ASP.Net Web API 2, you would need to use the Microsoft.AspNet.WebApi.Cors NuGet package. To install this package, you can execute the below command from the NuGet Package Manager Console.

Install-Package Microsoft.AspNet.WebApi.Cors
 

I will discuss about CORS support later.

Steps To Be Followed For This Session

These below mentioned steps will be the continuation of previous  Part One session. So, first you must follow my Part One session. 

Step 1

Add another new project for consuming Web API services. Here I have created an MVC web application for our client application. 
 
Go to Solution Explorer > Add > New Project > Select asp.net MVC web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK 
 
Step 2
 
Add a new MVC Controller.
 
Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.
 
Step 3
 
Here I have added "Part1" Action into "Home" Controller. Please write the following code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net.Http;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace SatyaConsumingApi.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         public ActionResult Part1()  
  13.         {  
  14.             return View();  
  15.         }  
  16.   
  17.     }  
  18. }  
Step 4
 
Add view for the action & design. Right Click on Action Method (here right click on form action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. 
 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Satyaprakash - Fetch data from WebApi using jquery";  
  3. }  
  4.   
  5. <style>  
  6.     table {  
  7.         font-family: arial, sans-serif;  
  8.         border-collapse: collapse;  
  9.         width: 100%;  
  10.     }  
  11.   
  12.     td, th {  
  13.         border: 1px solid #dddddd;  
  14.         text-align: left;  
  15.         padding: 8px;  
  16.     }  
  17.   
  18.     tr:nth-child(even) {  
  19.         background-color: #dddddd;  
  20.     }  
  21.   
  22. </style>  
  23.   
  24. <div>  
  25.     <div style="padding:10px ; align-content:center">  
  26.         <fieldset>  
  27.             <legend style="font-family:Arial Black;color:blue">Get Data From Web API Using JQuery As Per Selection</legend>  
  28.   
  29.             <input id="rad1GetData" type="radio" name="Full Name" class="btn btn-default" />  
  30.             <label style="color:green">  
  31.                 Get Full Name  
  32.             </label>     
  33.   
  34.             <input id="rad2GetData" type="radio" name="Full Name" class="btn btn-default" />  
  35.             <label style="color:orangered">  
  36.                 Get First Name  
  37.             </label>    
  38.   
  39.             <input id="rad3GetData" type="radio" name="Full Name" class="btn btn-default" />  
  40.             <label style="color:red">  
  41.                 Get Last Name  
  42.             </label>    
  43.         </fieldset>  
  44. </div>  
  45.   
  46.     <div id="updatePanel" style="width:90%; margin:0 auto; padding:10px">  
  47.   
  48.     </div>  
  49. </div>  
  50. @section Scripts{  
  51.     <script>  
  52.         $(document).ready(function () {  
  53.             var apiBaseUrl = "http://localhost:47250/";  
  54.             $('#rad1GetData').click(function () {  
  55.                 $.ajax({  
  56.                     url: apiBaseUrl + 'api/satya',  
  57.                     type: 'GET',  
  58.                     dataType: 'json',  
  59.                     success: function (data) {  
  60.                         var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  61.                         var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Full Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  62.                         $table.append($header);  
  63.                         $.each(data, function (i, val) {  
  64.                             var $row = $('<tr/>');  
  65.                             $row.append($('<td/>').html(val.FirstName + ' ' + val.LastName));  
  66.                             $row.append($('<td/>').html(val.EmailID));  
  67.                             $row.append($('<td/>').html(val.City));  
  68.                             $row.append($('<td/>').html(val.Country));  
  69.                             $table.append($row);  
  70.                         });  
  71.                         $('#updatePanel').html($table);  
  72.                     },  
  73.                     error: function () {  
  74.                         alert('Error!');  
  75.                     }  
  76.                 });  
  77.             });  
  78.   
  79.             $('#rad2GetData').click(function () {  
  80.                 $.ajax({  
  81.                     url: apiBaseUrl + 'api/satya',  
  82.                     type: 'GET',  
  83.                     dataType: 'json',  
  84.                     success: function (data) {  
  85.                         var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  86.                         var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">First Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  87.                         $table.append($header);  
  88.                         $.each(data, function (i, val) {  
  89.                             var $row = $('<tr/>');  
  90.                             $row.append($('<td/>').html(val.FirstName));  
  91.                             $row.append($('<td/>').html(val.EmailID));  
  92.                             $row.append($('<td/>').html(val.City));  
  93.                             $row.append($('<td/>').html(val.Country));  
  94.                             $table.append($row);  
  95.                         });  
  96.                         $('#updatePanel').html($table);  
  97.                     },  
  98.                     error: function () {  
  99.                         alert('Error!');  
  100.                     }  
  101.                 });  
  102.             });  
  103.   
  104.             $('#rad3GetData').click(function () {  
  105.                 $.ajax({  
  106.                     url: apiBaseUrl + 'api/satya',  
  107.                     type: 'GET',  
  108.                     dataType: 'json',  
  109.                     success: function (data) {  
  110.                         var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  111.                         var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Last Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  112.                         $table.append($header);  
  113.                         $.each(data, function (i, val) {  
  114.                             var $row = $('<tr/>');  
  115.                             $row.append($('<td/>').html(val.LastName));  
  116.                             $row.append($('<td/>').html(val.EmailID));  
  117.                             $row.append($('<td/>').html(val.City));  
  118.                             $row.append($('<td/>').html(val.Country));  
  119.                             $table.append($row);  
  120.                         });  
  121.                         $('#updatePanel').html($table);  
  122.                     },  
  123.                     error: function () {  
  124.                         alert('Error!');  
  125.                     }  
  126.                 });  
  127.             });  
  128.         });  
  129.     </script>  
  130. }  
Code Description
 
For radio buttons.
  1. <input id="rad1GetData" type="radio" name="Full Name" class="btn btn-default" />  
  2.            <label style="color:green">  
  3.                Get Full Name  
  4.            </label>     
  5.   
  6.            <input id="rad2GetData" type="radio" name="Full Name" class="btn btn-default" />  
  7.            <label style="color:orangered">  
  8.                Get First Name  
  9.            </label>    
  10.   
  11.            <input id="rad3GetData" type="radio" name="Full Name" class="btn btn-default" />  
  12.            <label style="color:red">  
  13.                Get Last Name  
  14.            </label>   
Here I added jquery code for getting data from the backend which means SQLserver using web API. I added three radio buttons with different Ids.
  1. <script>  
  2.         $(document).ready(function () {  
  3.             var apiBaseUrl = "http://localhost:47250/";  
  4.             $('#rad1GetData').click(function () {  
  5.                 $.ajax({  
  6.                     url: apiBaseUrl + 'api/satya',  
  7.                     type: 'GET',  
  8.                     dataType: 'json',  
  9.                     success: function (data) {  
  10.                         var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  11.                         var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Full Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  12.                         $table.append($header);  
  13.                         $.each(data, function (i, val) {  
  14.                             var $row = $('<tr/>');  
  15.                             $row.append($('<td/>').html(val.FirstName + ' ' + val.LastName));  
  16.                             $row.append($('<td/>').html(val.EmailID));  
  17.                             $row.append($('<td/>').html(val.City));  
  18.                             $row.append($('<td/>').html(val.Country));  
  19.                             $table.append($row);  
  20.                         });  
  21.                         $('#updatePanel').html($table);  
  22.                     },  
  23.                     error: function () {  
  24.                         alert('Error!');  
  25.                     }  
  26.                 });  
  27.             });  
  28.   
  29.             $('#rad2GetData').click(function () {  
  30.                 $.ajax({  
  31.                     url: apiBaseUrl + 'api/satya',  
  32.                     type: 'GET',  
  33.                     dataType: 'json',  
  34.                     success: function (data) {  
  35.                         var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  36.                         var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">First Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  37.                         $table.append($header);  
  38.                         $.each(data, function (i, val) {  
  39.                             var $row = $('<tr/>');  
  40.                             $row.append($('<td/>').html(val.FirstName));  
  41.                             $row.append($('<td/>').html(val.EmailID));  
  42.                             $row.append($('<td/>').html(val.City));  
  43.                             $row.append($('<td/>').html(val.Country));  
  44.                             $table.append($row);  
  45.                         });  
  46.                         $('#updatePanel').html($table);  
  47.                     },  
  48.                     error: function () {  
  49.                         alert('Error!');  
  50.                     }  
  51.                 });  
  52.             });  
  53.   
  54.             $('#rad3GetData').click(function () {  
  55.                 $.ajax({  
  56.                     url: apiBaseUrl + 'api/satya',  
  57.                     type: 'GET',  
  58.                     dataType: 'json',  
  59.                     success: function (data) {  
  60.                         var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  61.                         var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">Last Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  62.                         $table.append($header);  
  63.                         $.each(data, function (i, val) {  
  64.                             var $row = $('<tr/>');  
  65.                             $row.append($('<td/>').html(val.LastName));  
  66.                             $row.append($('<td/>').html(val.EmailID));  
  67.                             $row.append($('<td/>').html(val.City));  
  68.                             $row.append($('<td/>').html(val.Country));  
  69.                             $table.append($row);  
  70.                         });  
  71.                         $('#updatePanel').html($table);  
  72.                     },  
  73.                     error: function () {  
  74.                         alert('Error!');  
  75.                     }  
  76.                 });  
  77.             });  
  78.         });  
  79.     </script> 
Here I have added the web API URL I created in my previous session.
  1. var apiBaseUrl = "http://localhost:47250/";  
In the radio button click event I added url with controller name as created in the web API section.
  1. $('#rad1GetData').click(function () {  
  2.                 $.ajax({  
  3.                     url: apiBaseUrl + 'api/satya'
Here satya is the name of the controller and this controller section description will be found in my previous section.
 
You will get this url path from WebApiConfig.cs file from App_Start folder of SatyaWebApi project.
  1. config.Routes.MapHttpRoute(  
  2.                name: "DefaultApi",  
  3.                routeTemplate: "api/{controller}/{id}",  
  4.                defaults: new { id = RouteParameter.Optional }  
  5.            ); 
After sucessful execution, the data will be shown in a table for corresponding column header.
  1. success: function (data) {  
  2.                         var $table = $('<table/>').addClass('table table-responsive table-striped table-bordered');  
  3.                         var $header = $('<thead/>').html('<tr><th style="background-color: Yellow;color: blue">First Name</th><th style="background-color: Yellow;color: blue">Email</th><th style="background-color: Yellow;color: blue">City</th><th style="background-color: Yellow;color: blue">Country</th></tr>');  
  4.                         $table.append($header);  
  5.                         $.each(data, function (i, val) {  
  6.                             var $row = $('<tr/>');  
  7.                             $row.append($('<td/>').html(val.FirstName));  
  8.                             $row.append($('<td/>').html(val.EmailID));  
  9.                             $row.append($('<td/>').html(val.City));  
  10.                             $row.append($('<td/>').html(val.Country));  
  11.                             $table.append($row);  
  12.                         });  
  13.                         $('#updatePanel').html($table);  
  14.                     } 
If there is any connection issue or code related issue then an error message will be shown to the end user.
  1. error: function () {  
  2.      alert('Error!');  

The same procedure is to be follwed for other remaining radio buttons.
  • Using the First radio button id (#rad1GetData) the full name of the employee will be shown.
  • Using the Second radio button id (#rad2GetData) the first name of the employee will be shown.
  • Using the Third radio button id (#rad3GetData) the last name of the employee will be shown.

Step 5

In _Layout.cshtml file I have customized the footer section as shown below.
  1. <footer>  
  2. <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  3. </footer> 
Step 6
 
Here we need to start both applications as the client application will consume services from the web API application. Right click on the solution > Properties > Select "Multiple startup projects" > Change Action of both Projects to Start > Apply > Ok 
 
 
 
OUTPUT
 
The url of the MVC web aplication to consume Web API. Here both MVC web app and web APIurl will run simultaneously side by side.
 
http://localhost:12477/Home/Part1 >> url of MVC web aplication
 
http://localhost:47250/ >> Web Api url
 
 
 
For Full Name Radio Button.
 
 
 
For First Name Radio Button.
 
 
 
For Last Name Radio Button. 
 
 
 
SUMMARY
  • How a MVC web application consumes Web API services.
  • How to implement  Web API services in JQuery.


Similar Articles