ASP.Net connect to database using HttpHandler ASHX file
July 1st, 2009 | Posted in ASP.Net, Web | by Shyam
Advertisement
![]() |
Another alternative way to connect to database in ASP.Net is using ASHX file. The example we use is the same Customer information application given in my Previous Post which connects to the Northwind database and shows the available customers in dropdownlist of an aspx web page. Upon selecting each customer the Customer details will be displayed. Inorder to make AJAX calls, the latest version of the jQuery library should be referenced which can be downloaded from here. |
The design code of Customers.aspx
|
The codebehind in which data is retrieved from customers table of Northwind database and bound to a dropdownlist showing company name and having CustomerID as value field.
|
ASHX files are convenient ways to deliver partial content to a web page. They are actually HttpHandlers and responsible for processing incoming HTTP requests and providing the appropriate response. They are often used to deliver binary content such as images or files that are stored in database or outside of the web application file system. For delivering small amounts of html to be plugged into a particular position on a web page, they are extremely useful. Add New Item and choose Generic Handler file type and give the file name as “FetchCustomer.ashx”. A template for a class that inherits from IHttpHandler will be opened which contain one method-ProcessRequest( ) and a property-IsReusable( ). The entire FetchCustomer.aspx which generates a response to the Ajax call and creates output onto the caller page itself using context.Response object from the data retrieved to DataReader object which is from Customer table related to the particular CustomerID passed as Request.QueryString Parameter.
|
Now to call the HttpHandler of ASHX file, use the JQuery load function with QueryString parameter (exactly same as $.load( ) approach which was written in Previous Post) as shown below.
|