Using Web API With ASP.NET Web Forms - Part Seven

Hello guys, I’m back with my ASP.NET Web API series. In one of my previous articles, one guy asked me how can we use Web API with Web Forms in Visual Studio. Let’s a look at ASP.NET Web API series,

It’s pretty simple. Go ahead, open Visual Studio 2013, go to New and choose the Project.
 


Expand Installed > Templates > Visual C# and choose ASP.NET Web Application from the menu, give a reasonable name to your Web API project, which you want to do and finally click “OK” button.
 


From the given templates, select empty template and add a core reference of the Web Forms.
 


Here, my project is ready for use. In Solution Explorer, you can see the models folder and code at the backend Global.asax file, which is responsible for containing the URL route.
 


I want to call Web API with JavaScript and jQuery. Hence, add the form NuGet Package Manager for the current project. Right click on the project and select NuGet.
 


With the help of the following screenshot, you can install jQuery to your project:
 


Now add a model class, right click Models folder and add a class to it.
 


Select a class and give a reasonable name to your model class.
 


In the model class, I’ve created five properties of the student details.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace WebAPIWithWebForm.Models  
  7. {  
  8.     public class Student  
  9.     {  
  10.         public int StudRollNO { getset; }  
  11.         public string StudName { getset; }  
  12.         public string StudAddress { getset; }  
  13.         public int StudMONO { getset; }  
  14.         public string StudCourse { getset; }  
  15.   
  16.     }  
  17. }  


Now, I need to add a Web API Controller class to my project. It will handle HTTP requests for the Web API. Right click on the project and add a New Item.
 


Select Web API Controller class from the list and give it a proper name.

Thus, my College Controller that is Web API Controller drives from API Controller. The data of Student is stored in a fixed array inside the controller class. Click to resolve it from the Model class.
 


The GetAllStudents method returns the entire list of the students as an IEnumerable<Student> type.

The GetStudent method returns a single student record by its ID. If there is no record of matching ID, it will return the null value.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using WebAPIWithWebForm.Models;  
  8.   
  9. namespace WebAPIWithWebForm  
  10. {  
  11.     public class CollegeController : ApiController  
  12.     {  
  13.         Student[] stud = new Student[]  
  14.         {  
  15.             new Student{StudRollNO=1, StudName="Amit",   
  16.             StudAddress="Noida", StudMONO=123, StudCourse="MCA"},  
  17.             new Student{StudRollNO=2, StudName="Rahgvendra",   
  18.             StudAddress="Hardoi", StudMONO=321, StudCourse="BCA"},  
  19.             new Student{StudRollNO=3, StudName="Ankur",   
  20.             StudAddress="Lucknow", StudMONO=567, StudCourse="MBA"}  
  21.         };  
  22.         public IEnumerable<Student> GetallStudents()  
  23.         {  
  24.             return stud;  
  25.         }  
  26.         public IHttpActionResult GetStudent(int id)  
  27.         {  
  28.             var record = stud.FirstOrDefault(x => x.StudRollNO==id);  
  29.             if (record == null)  
  30.             {  
  31.                 return NotFound();  
  32.             }  
  33.             return Ok(record);  
  34.         }        
  35.     }  
  36. }   


Thus, if you call Web API with jQuery, you need to add a Web Form, give a name to it and hit the Add button.
 


Initially, add a reference to the jQuery source file in the head section. I’m using here some script of JavaScript and jQuery. jQuery getJSON function sends an AJAX request. Make a loop for the list of the students and add a table row for the students. Finally, append the row.
 


Create a table in the Web form as well. Similar to the property in the Model class, enter the Student details.
 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Students.aspx.cs" Inherits="WebAPIWithWebForm.Test" %>  
  2.   
  3.     <!DOCTYPE html>  
  4.     <html xmlns="http://www.w3.org/1999/xhtml">  
  5.   
  6.     <head runat="server">  
  7.         <title></title>  
  8.   
  9.         <script src="Scripts/jquery-3.0.0.min.js"></script>  
  10.   
  11.         <script type="text/javascript">  
  12.             function getStudents() {  
  13.                 $.getJSON("api/College",  
  14.                     function(data) {  
  15.                         $('#stud').empty(); // Clear table body.  
  16.   
  17.                         // Loop through the list of students.  
  18.                         $.each(data, function(key, val) {  
  19.                             // Add a table row for the student.  
  20.                             var row = '<tr><td>' + val.StudName +  
  21.                                 '</td><td>' + val.StudAddress + '</td><td>' +  
  22.                                 val.StudMONO + '</td><td>' + val.StudCourse +  
  23.                                 '</td></tr>';  
  24.                             $("#stud").append(row);  
  25.   
  26.                         });  
  27.                     });  
  28.             }  
  29.             $(document).ready(getStudents);  
  30.         </script>  
  31.   
  32.     </head>  
  33.   
  34.     <body>  
  35.         <form id="form1" runat="server">  
  36.             <h2> Here is the Students Record</h2>  
  37.             <table>  
  38.                 <thead>  
  39.                     <tr>  
  40.                         <th>StudName</th>  
  41.                         <th>StudAddress</th>  
  42.                         <th>StudMONO</th>  
  43.                         <th>StudCourse</th>  
  44.                     </tr>  
  45.                 </thead>  
  46.                 <tbody id="stud">  
  47.                 </tbody>  
  48.             </table>  
  49.         </form>  
  50.     </body>  
  51.   
  52.     </html>  
For Web API with Web Forms, this is the main step to add routing information, that routed to the controller directly. For it, add a namespace. 
  1. using WebAPIWithWebForm.Models;  
Add some implementation, as shown below:
 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Routing;  
  6. using System.Web.Security;  
  7. using System.Web.SessionState;  
  8. using System.Web.Http;  
  9.   
  10. namespace WebAPIWithWebForm {  
  11.     public class Global: System.Web.HttpApplication {  
  12.         protected void Application_Start(object sender, EventArgs e) {  
  13.             RouteTable.Routes.MapHttpRoute(  
  14.                 name: "MyAPI",  
  15.                 routeTemplate: "api/{controller}/{id}",  
  16.                 defaults: new {  
  17.                     id = System.Web.Http.RouteParameter.Optional  
  18.                 }  
  19.             );  
  20.         }  
  21.     }  
  22. }  
Save your project and call the respective Controller along with API. Hence, you can see, we got our Controller’s GetAllStudents method.
 


Now, call Web Form page, where you’ll get your expected output.
 
 

Thanks for reading this article. Stay tuned with us for more on ASP.NET Web API.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now