In this article I will explain with an example, how to use Generic HTTP Handler (ASHX) in ASP.Net MVC Razor.
The Generic HTTP Handler (ASHX) will be using Entity Framework to populate data from database and the output will be returned in JSON format.
The Generic HTTP Handler (ASHX) will be called using a jQuery Client which will read the JSON values and populate it into an HTML Table in ASP.Net MVC Razor.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Adding Generic Handler
You will need to add a new Generic HTTP Handler (ASHX) file using Add New Item Dialog of Visual Studio as shown below.
The JSON Generic HTTP Handler
The following JSON Generic HTTP Handler (ASHX) gets the records from the Customers table using Entity Framework and returns it in JSON format.
There JSON Generic HTTP Handler (ASHX) 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 (ASHX) using JavaScript or jQuery.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace Generic_Handler_MVC
{
///<summary>
/// Summary description for Handler
///</summary>
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)
{
using (CustomerEntities entities = new CustomerEntities())
{
var customers = from p in entities.Customers
where p.CustomerId == customerId || customerId == 0
select p;
return (new JavaScriptSerializer().Serialize(customers.ToList()));
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
View
The View consists of an HTML TextBox and an HTML Button assigned with a jQuery click event handler.
The GetCustomers JavaScript function is called inside the jQuery document ready event handler and also on Button Click event handler.
The Generic HTTP Handler (ASHX) is called using the jQuery getJSON function. The value of the CustomerId parameter is fetched from the TextBox while the callback parameter is passed as “?” as there’s no callback function in this scenario.
Once the response is received, it is displayed in an HTML Table.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
GetCustomers();
$("#btnSearch").click(function () {
GetCustomers();
});
});
function GetCustomers() {
var table = $("#tblCustomers");
var customerId = $.trim($("#txtCustomerId").val());
$.getJSON('/Handler.ashx?customerId=' + customerId + '&callback=?', function (result) {
table.find("tr:not(:first)").remove();
$.each(result, function (i, customer) {
var row = table[0].insertRow(-1);
$(row).append("<td />");
$(row).find("td").eq(0).html(customer.CustomerId);
$(row).append("<td />");
$(row).find("td").eq(1).html(customer.Name);
$(row).append("<td />");
$(row).find("td").eq(2).html(customer.Country);
});
});
}
</script>
CustomerId:
<input type="text" id="txtCustomerId"/>
<input type="button" id="btnSearch" value="Search"/>
<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>
</body>
</html>
Screenshot
Downloads