Call Web API Using JQuery AJAX In ASP.NET Core Web Applications

In this article, you will learn how to create a simple Web API and pass the data, and call the Web API using jQuery AJAX and parse into HTML in ASP.NET Web Application (.NET Core),

In this article, we will discuss how to invoke API, using AJAX in ASP.NET .Core. This article will explain how to create Web API in ASP.NET Core and call that Web API, using jQuery AJAX in Razor.

Milestone
  • Create a simple ASP.NET Core Web Application project.
  • Add a Model.
  • Create Web API returning list of the data.
  • Create a new Controller and View.
  • Write jQuery AJAX code to invoke Web API and parse into HTML.
Create simple ASP.NET Core Web Application.

Creating a Web Application is similar to creating a ASP.NET MVC Web Application.

Step 1

Open Visual Studio.
 
Step 2

Go to File => New Project.
  1. Select Visual C# => .NET Core => ASP.NET Core Web Application(.NET Core).
  2. Name your Solution (DemoApp), Project (DemoApp) and click OK.

    ASP.NET Core Application
  1. Select Web Application.
  2. Change Authentication to Individual Accounts.

    ASP.NET Core Application
Now, Visual Studio 2017 will create a project for you.

Once the project is created, you will see the screen, as shown below.

ASP.NET Core Application

Add Model

Step 1

Create a new folder under Models folder named Student.
 
Step 2

Add New Class named as PersonalDetail.

Step 3

Add the lines of codes given below to PersonalDetail class.

ASP.NET Core Application
Code sample

  1. public class PersonalDetail  
  2.     {  
  3.         public string RegNo { getset; }  
  4.         public string Name { getset; }  
  5.         public string Address { getset; }  
  6.         public string PhoneNo { getset; }  
  7.         public DateTime AdmissionDate { getset; }  
  8.     }   
Add Web API

Step 1

Right click on Controller Folder and Add => Controller.

Step 2

Select API Controller - Empty.

Step 3

Click Add.

ASP.NET Core Application

Step 4

Name the Web API as StudentAPI.

ASP.NET Core Application by Nishan Aryal

Step 5

Now, create [HttpGet] type method called GetAllStudents().

Your method should look, as shown below.

ASP.NET Core Application by Nishan Aryal

Code sample
  1. public class StudentAPIController : Controller  
  2.    {  
  3.        // GET: api/GetAllStudents  
  4.        [HttpGet]  
  5.        public IEnumerable<PersonalDetail> GetAllStudents()  
  6.        {  
  7.            List<PersonalDetail> students = new List<PersonalDetail>  
  8.            {  
  9.            new PersonalDetail{  
  10.                               RegNo = "2017-0001",  
  11.                               Name = "Nishan",  
  12.                               Address = "Kathmandu",  
  13.                               PhoneNo = "9849845061",  
  14.                               AdmissionDate = DateTime.Now  
  15.                               },  
  16.            new PersonalDetail{  
  17.                               RegNo = "2017-0002",  
  18.                               Name = "Namrata Rai",  
  19.                               Address = "Bhaktapur",  
  20.                               PhoneNo = "9849845062",  
  21.                               AdmissionDate = DateTime.Now  
  22.                              },                
  23.            };  
  24.            return students;  
  25.        }  
  26.    }  
Call Web API using Jquery AJAX

Creating Controller and View

You can create a new controller and view for displaying the data returned by Web API. For Now I used Index Method of Home Controller to call Web API just created.

Step 1

Open Views => Home => Index.cshtml

Step 2

Lets remove unnecessady HTML codes.

Step 3

Add Reference to Jquery.

Step 4

Let's add a simple HTML Table to display data returned from Web API in tablular form.

ASP.NET Core Application by Nishan Aryal
Code sample 
  1. //Reference to JQuery  
  2. <script src="~/lib/jquery/dist/jquery.min.js"></script>   
  3.   
  4.   
  5. <div class="panel panel-primary">  
  6.     <div class="panel-heading">  
  7.         Test Data from API  
  8.     </div>   <!--en dof panel-heading -->
  9.     <div class="panel-body">  
  10.         <table class="table table-bordered" id="Table">  
  11.             <tr>  
  12.                 <th>Regd No</th>  
  13.                 <th>Name</th>  
  14.                 <th>Address</th>  
  15.                 <th>Phone No</th>  
  16.                 <th>Admission Date</th>  
  17.             </tr>   <!--end of table-row -->
  18.         </table>   <!--end of table -->
  19.     </div> <!--end of Panel-body -->      
  20. </div> <!--end of Panel -->  
Step 5

Let's add jQuery scripts to call Web API, which we just created and parse the data sent by API to HTML. AJAX looks, as shown below.

Step 4: Lets add a simple HTML Table to display data returned from Web API in tablular form.
 
Code sample
  1. <script>  
  2.     $(document).ready(function () {  
  3.         $.ajax({  
  4.             type: "GET",  
  5.             url: "/api/StudentAPI/GetAllStudents",  
  6.             contentType: "application/json; charset=utf-8",  
  7.             dataType: "json",  
  8.             success: function (data) {  
  9.                 //alert(JSON.stringify(data));                  
  10.                 $("#DIV").html('');   
  11.                 var DIV = '';  
  12.                 $.each(data, function (i, item) {  
  13.                     var rows = "<tr>" +  
  14.                         "<td id='RegdNo'>" + item.regNo + "</td>" +  
  15.                         "<td id='Name'>" + item.name + "</td>" +  
  16.                         "<td id='Address'>" + item.address + "</td>" +  
  17.                         "<td id='PhoneNo'>" + item.phoneNo + "</td>" +  
  18.                         "<td id='AdmissionDate'>" + Date(item.admissionDate,  
  19.                          "dd-MM-yyyy") + "</td>" +  
  20.                         "</tr>";  
  21.                     $('#Table').append(rows);  
  22.                 }); //End of foreach Loop   
  23.                 console.log(data);  
  24.             }, //End of AJAX Success function  
  25.   
  26.             failure: function (data) {  
  27.                 alert(data.responseText);  
  28.             }, //End of AJAX failure function  
  29.             error: function (data) {  
  30.                 alert(data.responseText);  
  31.             } //End of AJAX error function  
  32.   
  33.         });         
  34.     });  
  35. </script>  
More about jQuery AJAX

AJAX is a developer's dream(Defn from W3Schools), because you can

  • Update a Web page without reloading the page.
  • Request data from a server - after the page has loaded.
  • Receive data from a server - after the page has loaded.
  • Send the data to a Server - in the background.
To learn the basics of AJAX, please visit https://www.w3schools.com/xml/ajax_intro.asp
 
Parts of AJAX

type:                 GET/POST
url :                   URL ofWeb API to pull/push data
contentType:    application/json
dataType:         json
success:          function()
failure:              function()
error:                function()  
 
Application Execution

Now, run the Index Mthod of Home Page Controller and you will be able to retrieve all the data passed from Web API. If you navigate to the Web API, which we just created, it looks as shown below.

How to call Web API using JQuery AJAX in ASP.NET Core Web Applications
Now, let's navigate to Index Method of Home Contoller (Where we load WebAPI using JQuery AJAX)

JSON data shown above is parsed here.
 
How to call Web API using JQuery AJAX in ASP.NET Core Web Applications  

Checking data, using Browser console

Let's check the data shown above, using Browser console too. The data in the console looks as shown below.

Checking data using Browser Console

If you like to show the data only after clicking any buttons, you can customize the script section to load the data.

Summary

I hope you learned:
  • How to create a simple SP.NET Web Application (.NET Core).
    • How to create a simple Web API.
    • Pass data from Web API.
    • Call Web API, using AJAX and parse the data to HTML.