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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace webapp
{
   
public class Material
    {
        
public int id { get; set; }
       
public string Mname { get; set; }
       
public decimal cost { get; set; }
       
public string Type { get; set; }
    }

}

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:


namespace webapp

{

  using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Net;
using
System.Net.Http;
using
System.Web.Http;
using
webapp;
 
public class MaterialsController : ApiController
    {

        
       
Material[] materials = new Material[]
        {

new
Material{id= 1,Mname="KeyBoard",Type="Hardware",cost=700},
new
Material{id=2,Mname="Monitor",Type="Hardware",cost=21000},
new
Material{id=3 ,Mname="Orange",Type="Fruit",cost=100},
        };

        public IEnumerable<Material> GetAllMaterials()
        {
           
return materials;

        }
       
public Material GetMaterialById(int Id)
       {
           
var material = materials.FirstOrDefault((m) => m.id == Id);
           
if (material == null)
            {

                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            return material;
        }

        public IEnumerable<Material> GetMaterialBYType(string type)

        {

      return materials.Where((m) => string.Equals(m.Type, type,

                           StringComparison.OrdinalIgnoreCase));

        }

    }

}

   


Step 4:
Add the Routing Information

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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Optimization;

using System.Web.Routing;

using System.Web.Security;

using webapp;

using System.Web.Http;

namespace webapp

{

    public class Global : HttpApplication

    {

        void Application_Start(object sender, EventArgs e)

        {

            RouteTable.Routes.MapHttpRoute(

                name: "DefaultApi",

                routeTemplate: "api/{controller}/{Id}",

                defaults: new { Id = System.Web.Http.RouteParameter.Optional }

                );

            // Code that runs on application startup

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            AuthConfig.RegisterOpenAuth();

        }

 

        void Application_End(object sender, EventArgs e)

        {

            //  Code that runs on application shutdown

 

        }
         
void Application_Error(object sender, EventArgs e)

        {

            // Code that runs when an unhandled error occurs

 

        }

    }

}

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:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="webapp._Default" %>

<asp:Content ID="HeaderContent1" runat="server" ContentPlaceHolderID="HeadContent">

    <script src="Scripts/jquery-1.7.1.min.js"></script>

  

     <script type="text/javascript">

 

        function getMaterials() {

 

            $.getJSON("api/materials",

                function (Data) {

 

                $('#materials').empty();

 

                $.each(Data, function (key, val) {

 

                    var row = val.Mname + val.cost;

 

                    $('<tr>', { text: row })

                    .appendTo($('#materials'));

                });

            });

        }

        $(document).ready(getMaterials);

    </script>

    </asp:Content>

 

 

<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">

     <h2>All Type Items</h2>

     <table>

    <thead>

        <tr><th>Name </th><th>cost</th></tr>

    </thead>

    <tbody id="materials">

    </tbody>

    </table>

</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

Up Next
    Ebook Download
    View all
    Learn
    View all