In this article I will explain with an example, how to call (consume) JSON Generic HTTP Handler (ASHX) on Client Side using JavaScript in ASP.Net using C# and VB.Net.
When the JSON Generic HTTP Handler will be called using JavaScript, the records from database is fetched and returned in JSON format to JavaScript callback function.
 
 
Database
I have made use of the following table Customers with the schema as follows.
Call (Consume) JSON Generic HTTP Handler (ASHX) using JavaScript in ASP.Net
 
I have already inserted few records in the table.
Call (Consume) JSON Generic HTTP Handler (ASHX) using JavaScript in ASP.Net
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Adding Generic Handler
You will need to add a new Generic Handler (ASHX) file using Add New Item Dialog of Visual Studio as shown below.
Call (Consume) JSON Generic HTTP Handler (ASHX) using JavaScript in ASP.Net
 
 
Building a JSON Generic HTTP Handler
The following JSON Generic HTTP Handler gets the records from the Customers table and returns it in JSON format.
There JSON Generic HTTP Handler accepts two optional QueryString parameters.
1. customerId – If a valid ID is passed, it will return the record only for the specific Customer.
2. callback – This parameter holds the value of the Callback function which will be executed by the client side script when the response is received.
The callback feature is generally used when calling the JSON Generic HTTP Handler using JavaScript or jQuery.
C#
<%@ WebHandler Language="C#" Class="Handler" %>
 
using System;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.Script.Serialization;
 
public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string callback = context.Request.QueryString["callback"];
        int customerId = 0;
        int.TryParse(context.Request.QueryString["customerId"], out customerId);
        string json = this.GetCustomersJSON(customerId);
        if (!string.IsNullOrEmpty(callback))
        {
            json = string.Format("{0}({1});", callback, json);
        }
       
        context.Response.ContentType = "text/json";
        context.Response.Write(json);
    }
 
    private string GetCustomersJSON(int customerId)
    {
        List<object> customers = new List<object>();
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT * FROM Customers WHERE CustomerId = @CustomerId OR @CustomerId = 0";
                cmd.Parameters.AddWithValue("@CustomerId", customerId);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(new
                        {
                            CustomerId = sdr["CustomerId"],
                            Name = sdr["Name"],
                            Country = sdr["Country"]
                        });
                    }
                }
                conn.Close();
            }
            return (new JavaScriptSerializer().Serialize(customers));
        }
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
 
VB.Net
<%@ WebHandler Language="VB" Class="Handler" %>
 
Imports System
Imports System.Web
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Collections.Generic
Imports System.Web.Script.Serialization
 
Public Class Handler : Implements IHttpHandler   
    Public Sub ProcessRequest(ByVal context As HttpContextImplements IHttpHandler.ProcessRequest
        Dim callback As String = context.Request.QueryString("callback")
        Dim customerId As Integer = 0
        Integer.TryParse(context.Request.QueryString("customerId"), customerId)
        Dim json As String = Me.GetCustomersJSON(customerId)
        If Not String.IsNullOrEmpty(callback) Then
            json = String.Format("{0}({1});", callback, json)
        End If
        context.Response.ContentType = "text/json"
        context.Response.Write(json)
    End Sub
   
    Private Function GetCustomersJSON(customerId As IntegerAs String
        Dim customers As New List(Of Object)()
        Using conn As New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As New SqlCommand()
                cmd.CommandText = "SELECT * FROM Customers WHERE CustomerId = @CustomerId OR @CustomerId = 0"
                cmd.Parameters.AddWithValue("@CustomerId", customerId)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        customers.Add(New With { _
                          .CustomerId = sdr("CustomerId"), _
                          .Name = sdr("Name"), _
                          .Country = sdr("Country") _
                        })
                    End While
                End Using
                conn.Close()
            End Using
            Return (New JavaScriptSerializer().Serialize(customers))
        End Using
    End Function
   
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class
 
 
HTML Markup
The following HTML Markup consists of an HTML Table, an HTML input TextBox and a Button control.
The Button has been assigned with a JavaScript onclick event handler.
<input type="text" id="txtCustomerId" />
<input type="button" id="btnSearch" value="Search" onclick="GetCustomers()" />
<hr />
<table id="tblCustomers" border="0" cellpadding="0" cellspacing="0">
    <tr>
        <th style="width: 90px">
            Customer Id
        </th>
        <th style="width: 120px">
            Name
        </th>
        <th style="width: 90px">
            Country
        </th>
    </tr>
</table>
 
 
Calling (Consuming) JSON Generic Handler (ASHX) using JavaScript
Inside the Window Onload event handler, the GetCustomers JavaScript function is called and also on Button Click event handler.
The JSON Generic HTTP Handler is called using a method called as JSONP (JSON with Padding).
Inside this method, an AJAX request is made by attaching dynamic SCRIPT tags.
The SRC attribute of the dynamic SCRIPT tag is set to the JSON Generic HTTP Handler along with the CustomerId parameter (value of the TextBox) and the callback parameter (name of the function to be executed when the response is received).
Next, the dynamic SCRIPT tag is attached to the HEAD element which executes it and ultimately calls the JSON Generic HTTP Handler.
Finally, once the response is received, the JavaScript function specified in the callback parameter i.e. PopulateCustomers gets called which displays the results from the database in HTML Table.
<script type="text/javascript">
    window.onload = function () {
        GetCustomers();
    };
 
    function GetCustomers() {
        var customerId = document.getElementById("txtCustomerId").value;
 
        //Create a SCRIPT element.
        var script = document.createElement("script");
 
        //Set the Type.
        script.type = "text/javascript";
 
        //Set the source to the URL the JSON Service.
        script.src = '<%=ResolveUrl("~/Handler.ashx") %>?customerId=' + customerId + '&callback=PopulateCustomers';
 
        //Append the script element to the HEAD section.
        document.getElementsByTagName("head")[0].appendChild(script);
    };
 
    function PopulateCustomers(response) {
        var tblCustomers = document.getElementById("tblCustomers");
 
        //Remove all rows.
        var rowCount = tblCustomers.rows.length;
        for (var i = rowCount - 1; i > 0; i--) {
            tblCustomers.deleteRow(i);
        }
 
        //Add the data rows.
        for (var i = 0; i < response.length; i++) {
            row = tblCustomers.insertRow(-1);
            var cell = row.insertCell(-1);
            cell.innerHTML = response[i].CustomerId;
 
            cell = row.insertCell(-1);
            cell.innerHTML = response[i].Name;
 
            cell = row.insertCell(-1);
            cell.innerHTML = response[i].Country;
        }
    }
</script>
 
 
Screenshot
Call (Consume) JSON Generic HTTP Handler (ASHX) using JavaScript in ASP.Net
 
 
Demo
 
 
Downloads