Display Records in HTML Page Using ASP.Net Web API 2

Introduction

The Web API is the Application Programming Interface (API) for both the web server and web browser. The API is a framework for building HTTP services that can be consumed by the clients, either by a browser, iPhone, tablets or a mobile. A server- side Web API is a programmatic interface to define the request/response message system, these are expressed in JSON or XML that are exposed via the web.

Features of Web API

  • Web API is open source
  • Used to make a non-SOAP based HTTP Service
  • Based of HTTP and easy to define, expose and consume in a RESTful way.
  • Web API does not have any cumbersome and tedious configuration like WCF REST service.
  • Web API is a lightweight architecture and is good for a device that has limited/reduced bandwidth (smartphones).

 Basic procedure for creating a Web API and consuming in a HTML page

  • Create a Web API
  • Adding a Model
  • Adding a controller
  • Consuming the Web API

Create a Web API

Start the Visual Studio and choose "New Project" then choose the "ASP.NET Web application" template.

Img1

After selecting the project, choose an Empty template and select the "Web API" under the  "Add folder and core reference for :"

img21

You may also choose a Web API project using the "Web API" template. The Web API template uses ASP.NET MVC to provide API help pages.

Adding a Model

Model class used for to represent the data and the data are used in our application. Web API automatically serializes our model to JSON, XML or some other format and then we write the serialize data into the body of the response message.

ModelClass

This is the code of the model class, where we create properties of the Student. 

  1. namespace StudentRecord  
  2. {  
  3.     public class Student  
  4.     {  
  5.         public int ID { getset; }  
  6.         public string Name { getset; }  
  7.         public string Class { getset; }  
  8.         public string Address { getset; }  
  9.         public int PercentageMarks { getset; }  
  10.     }  
  11. }  

Adding a controller

We use a controller for the handler of HTTP requests. In the project I added a controller and that controller returns a list of students or a single student as passed by ID.

ControllerClass

Add a Scaffold, select "Web API controller -Empty". Click Add.

ControllerAPI2

This is the controller class where we define the Get all the students function and get the student by id, these methods definitions are in the snippet below.  

  1. namespace StudentRecord.Controllers  
  2. {  
  3.     public class StudentsController : ApiController  
  4.     {  
  5.         Student[] st = new Student[]{  
  6.             new Student{ID=1, Name="Rajeev Ranjan",Address="pune", Class="IX", PercentageMarks=87},  
  7.             new Student{ID=2, Name="Manish Shrivastava",Address="pune", Class="IX", PercentageMarks=88},  
  8.             new Student{ID=3, Name="Chandan Singh",Address="Ranchi", Class="IX", PercentageMarks=99},  
  9.             new Student{ID=4, Name="Manish Singh",Address="Ranchi", Class="IX", PercentageMarks=85},  
  10.             new Student{ID=5, Name="Rohit",Address="New Delhi", Class="IX", PercentageMarks=79},  
  11.             new Student{ID=6, Name="Kunal",Address="New Delhi", Class="IX", PercentageMarks=64},  
  12.             new Student{ID=7, Name="Thomas Minz",Address="Hazaribagh", Class="IX", PercentageMarks=33},  
  13.             new Student{ID=8, Name="Santosh",Address="pune", Class="IX", PercentageMarks=56},  
  14.             new Student{ID=9, Name="Amrut Gholkhar",Address="Aurangabad", Class="IX", PercentageMarks=82},  
  15.             new Student{ID=10, Name="Gaurav Lahe",Address="Amrawati", Class="IX", PercentageMarks=98},  
  16.         };  
  17.         public IEnumerable<Student> GetAllStudent() {  
  18.             return st;  
  19.         }  
  20.         public IHttpActionResult GetStudents(int id)  
  21.         {  
  22.             var stud = st.FirstOrDefault((s) => s.ID == id);  
  23.             if(stud== null)  
  24.             {  
  25.                 return NotFound();  
  26.             }  
  27.             return Ok(stud);  
  28.         }  
  29.     }  
  30. }  

Consuming the Web API 

This is the final section of when we consume and disply in the HTML page, using jQuery and Ajax. Ajax calls the Web API and we use jQuery to make the Ajax calls.

SelectHtmlPage

If you have no jQuery file then install it from the Nuget Packet Manager. It is essential to attach the jQuery file inside the HTML page, if we missed that then jQuery and Ajax will not able to consume the Web API request and response object.

AddingJquery 
 
This is the HTML and jQuery codes to make the app possibilities come true.
  1. <html>  
  2. <head>  
  3.     <title>Student Record</title>  
  4. </head>  
  5. <body>  
  6.     <div>  
  7.         <h2>Student</h2>  
  8.         <table id="student" cellpadding="2" cellspacing="2" border="1" width="400px">  
  9.             <tr>  
  10.                 <td style="background-color: gray; color: white">ID</td>  
  11.                 <td style="background-color: gray; color: white">Name</td>  
  12.                 <td style="background-color: gray; color: white">Class</td>  
  13.                 <td style="background-color: gray; color:white">Percentage Marks</td>  
  14.                 <td style="background-color: gray; color:white">Address</td>  
  15.             </tr>  
  16.         </table>  
  17.     </div>  
  18.              
  19.     <div>  
  20.         <h2>Search by ID</h2>  
  21.   
  22.         <input type="text" size="5" id="stuId" />  
  23.         <input type="button" value="Search" onclick="find();" />  
  24.   
  25.         <p id="st"></p>  
  26.     </div>  
  27.     <script src="Scripts/jquery-2.1.1.js"></script>  
  28.     <script type="text/javascript">  
  29.   
  30.         var uri = 'api/students';  
  31.         $(document).ready(function () {  
  32.             $.getJSON(uri)  
  33.             .done(function (data) {  
  34.                 $.each(data, function (key, item) {  
  35.                     $('#student').append("<tr><td>" + item.ID + "</td>" + "<td>" + item.Name + "</td>" + "<td>" + item.Class + "</td>" + "<td>" + item.PercentageMarks + '%' + "</td>" + "<td>" + item.Address + "</td></tr>");  
  36.                 });  
  37.             });  
  38.         });  
  39.   
  40.         function formatItem(item) {  
  41.             return item.Name + '-' + item.PercentageMarks;  
  42.         }  
  43.         function find() {  
  44.             var id = $('#stuId').val();  
  45.             $.getJSON(uri + '/' + id)  
  46.             .done(function (data) {  
  47.                 $('#st').text(formatItem(data));  
  48.             })  
  49.             .fail(function (jqXHR, textStatus, err) {  
  50.                 $('#student').text('error' + err);  
  51.             })  
  52.         }  
  53.     </script>  
  54. </body>  
  55. </html>  

Output

This is the output of all the records fetched. 

Output1

When we select by ID then the result will shown as in the following.

Output2

When we enter the wrong (lower / upper) records then we get the following output message.

output3

Summary

In this article we learned how to make a Web API and how to consume it in a HTML page using jQuery and AJAX. We also covered the benefits of the Web API. HTTP is not just for serving up web pages, it is also a powerful platform for building an API that exposes data and services. Almost every platform can easily get the data from the Web API, either Tablet or website by HTTP.


Similar Articles