Technological Guide.

ASP.Net connect to database via AJAX using JQUERY

One of the ways to connect to database in ASP.Net is via AJAX using JQUERY by giving an example below 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.

Now create another file “FetchCustomer.aspx” with code behind option deselected. The entire FetchCustomer.aspx which generates a response to the Ajax call and creates output onto the caller page itself using Response object from the data retrieved to DataReader object which is from Customer table related to the particular CustomerID passed as Request.QueryString Parameter.

There are a number of ways jQuery can request the FetchCustomer.aspx page and handle the response. The first way we are going to illustrate is the load() function, which loads html from FetchCustomer.aspx The below code will be added in the head section of the Customers.aspx which will reference the lattest version of the JQuery library and as the page loads, $(document).ready( ) function will be applied to onchange event of the dropdownlist control. This functions gets the id of the div “CustomerDetails” of the page (“Customers.aspx”) within which it resides to load the html returned from the FetchCustomer.aspx page and passes the currently selected dropdownlist value in the querystring.

Another way alternative to $.load( ) funtion is the $.get( ) function which does exactly the same except the callback argument specifies what is to be done with the response from the Ajax request. Place this script in the head section of Customers.aspx. In $.get( ) function the query string value is passed along with the querystring name in { } brackets along with the query string name & value seperated by a colon(:). jQuery takes these values and constructs a querystring as part of the HTTP request, so that the page called is FetchCustomer.aspx?CustomerID=strCustomerID.

The other alternative method is $.ajax(). This is a more feature rich method in that it allows a range of options to be applied to manage different types of call, and error handling. Just place the below script in the head section of the FetchCustomer.aspx page.

You may also like to read

 

One Response to “ASP.Net connect to database via AJAX using JQUERY”

  1. This is Very good technique and is working can we done it using json object and how,please reply

Leave a Reply