Using Web API With ASP.NET Web Forms

Introduction

In this article, we will define how to use the Web API with ASP. Net Web Forms. The following is the procedure for using the Web API in Web Forms.

Step 1

First create the Web Form Project as in the following:

  • Open Visual Studio 2012
  • Click on "File" -> "New" -> "Project...".
  • From the New Project window select "ASP.NET Web Forms Application".
  • Change the name of application to "webapp".
  • Click on the "OK" button.

    img1.jpg

Step 2

Then add the Model Class as in the following:

  • Right-click on the solution in the Solution Explorer then select "Add" > "class"
  • Set the name of the class to "Material".
  • Click on the "OK" button.

    img5.jpg

    img2.jpg

Now we write this code for the class:

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace webapp  
  6. {  
  7.     public class Material  
  8.     {  
  9.         public int id { getset; }  
  10.         public string Mname { getset; }  
  11.         public decimal cost { getset; }  
  12.         public string Type { getset; }  
  13.     }  
  14.   
  15. }  

 

Step 3

Then add the controller as in the following:

  • Right-click on the solution in the Solution Explorer then select "Add" > "New item"
  • In the Installed Templates window select "Visual C#" > "Web"
  • Select the Web API Controller Class.
  • Change the name of the controller to "Materials".
  • Click on the "OK" button.

    new.jpg

Write this code in the Controller:

  1. namespace webapp  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.Linq;  
  6.     using System.Net;  
  7.     using System.Net.Http;  
  8.     using System.Web.Http;  
  9.     using webapp;  
  10.     public class MaterialsController : ApiController  
  11.     {  
  12.         Material[] materials = new Material[]  
  13.         {  
  14.             new Material{id= 1,Mname="KeyBoard",Type="Hardware",cost=700},  
  15.             new Material{id=2,Mname="Monitor",Type="Hardware",cost=21000},  
  16.             new Material{id=3 ,Mname="Orange",Type="Fruit",cost=100},  
  17.         };  
  18.         public IEnumerable<Material> GetAllMaterials()  
  19.         {  
  20.             return materials;  
  21.         }  
  22.         public Material GetMaterialById(int Id)  
  23.        {  
  24.             var material = materials.FirstOrDefault((m) => m.id == Id);  
  25.             if (material == null)  
  26.             {  
  27.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  28.             }  
  29.             return material;  
  30.         }  
  31.         public IEnumerable<Material> GetMaterialBYType(string type)  
  32.         {  
  33.       return materials.Where((m) => string.Equals(m.Type, type,  
  34.                            StringComparison.OrdinalIgnoreCase));  
  35.         }  
  36.     }  
  37. } 

Step 4: Add the Routing Information

In the Solution Explorer click on the "Global.asax" file and add this code in the file:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Optimization;  
  6. using System.Web.Routing;  
  7. using System.Web.Security;  
  8. using webapp;  
  9. using System.Web.Http;  
  10. namespace webapp  
  11. {  
  12.     public class Global : HttpApplication  
  13.     {  
  14.         void Application_Start(object sender, EventArgs e)  
  15.         {  
  16.             RouteTable.Routes.MapHttpRoute(  
  17.                 name: "DefaultApi",  
  18.                 routeTemplate: "api/{controller}/{Id}",  
  19.                 defaults: new { Id = System.Web.Http.RouteParameter.Optional }  
  20.                 );  
  21.             // Code that runs on application startup  
  22.             BundleConfig.RegisterBundles(BundleTable.Bundles);  
  23.             AuthConfig.RegisterOpenAuth();  
  24.         }  
  25.         void Application_End(object sender, EventArgs e)  
  26.         {  
  27.             //  Code that runs on application shutdown  
  28.         }  
  29.         void Application_Error(object sender, EventArgs e)  
  30.         {  
  31.             // Code that runs when an unhandled error occurs  
  32.         }  
  33.     }  
  34. }   

Step 5: Add the client side AJAX

Now we need to create the Web API that can be accessed by the client. We will add the jQuery to this HTML page.

On the Default.aspx page we will add this code:

 

  1. <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="webapp._Default" %>  
  2. <asp:Content ID="HeaderContent1" runat="server" ContentPlaceHolderID="HeadContent">  
  3.     <script src="Scripts/jquery-1.7.1.min.js"></script>  
  4.      <script type="text/javascript">  
  5.         function getMaterials() {  
  6.             $.getJSON("api/materials",  
  7.                 function (Data) {  
  8.                 $('#materials').empty();  
  9.                 $.each(Data, function (key, val) {  
  10.                     var row = val.Mname + val.cost;  
  11.                     $('<tr>', { text: row })  
  12.                     .appendTo($('#materials'));  
  13.                 });  
  14.             });  
  15.         }  
  16.         $(document).ready(getMaterials);  
  17.     </script>  
  18.     </asp:Content>  
  19. <asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">  
  20.      <h2>All Type Items</h2>  
  21.      <table>  
  22.     <thead>  
  23.         <tr><th>Name </th><th>cost</th></tr>  
  24.     </thead>  
  25.     <tbody id="materials">  
  26.     </tbody>  
  27.     </table>  
  28. </asp:Content>  

 

Now we add the reference of the jQuery file. We add this reference in the HeaderContent section in the Default.aspx page.

We can add this reference by draging from the Solution Explorer. In the Solution Explorer open the file "Scripts" and drag the jquery-1.7.1.min.js and place it in the HeaderContent section.      

 img4.jpg

Result

When we debug this application the AJAX makes a request to the "api/materials" and then the response is a list of items.

res.jpg


Similar Articles