AJAX using JQuery and ASP.net
This is my first article on JQuery. Although I am using JQuery for more than two years I was unable to write any article on that due to lack of time. In the following simple example I will try to explain how you can send AJAX request from you asp.net application using JQuery and web services. So let’s start our journey.
For this example I have used the Customers table from Northwind database.
Create a default.aspx page and add the following code in the body portion of the aspx page
<form id=”form1″ runat=”server”>
// asp.net dropdown list
<asp:DropDownList ID=”Customers” runat=”server” AutoPostBack=”false”>
</asp:DropDownList>
// div to hold the details regarding customers
<div id=”CustomerDetails” >
</div>
</form>
Just make sure that the AutoPostBack property of your DropdownList is set to false AutoPostBack=”false”.
Then go to the cs page i.e. defaul.aspx.cs and add the following code in the page Load method.
if(!IsPostBack)
{
// usually we define the connection string in web.config but for making it simple defined here
string connect = @”Data Source=.\SQLEXPRESS;Initial Catalog=NorthWind;User ID=sa;Password=password”;
//query to select customer data
string query = “SELECT CustomerID, CompanyName FROM Customers”;
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
Customers.DataSource = cmd.ExecuteReader();
Customers.DataValueField = “CustomerID”;
Customers.DataTextField = “CompanyName”;
Customers.DataBind();
}
}
}
Now add an entity class customer.cs and add the following code in it.
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
Now a webservice WebService.asmx in the project and add the following method in it.
[WebMethod]
public ClsCustomer GetCustomerDetailByID(string CustomerID)
{
try
{
Customer c = new Customer();
string connect = @”Data Source=.\SQLEXPRESS;Initial Catalog=NorthWind;User ID=sa;Password=password”;
string query = “SELECT CustomerID,CompanyName, Address, City, Region, PostalCode,” +
“Country, Phone, Fax FROM Customers WHERE CustomerID = @CustomerID”;
if (CustomerID != null )
{
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue(“CustomerID”, CustomerID);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
// Load the data in the customer object
c.CustomerID = rdr["CustomerID"].ToString();
c.CompanyName = rdr["CompanyName"].ToString();
c.Address = rdr["Address"].ToString();
c.City = rdr["City"].ToString();
c.Region = rdr["Region"].ToString();
c.PostalCode = rdr["PostalCode"].ToString();
c.Country = rdr["Country"].ToString();
c.Phone = rdr["Phone"].ToString();
c.Fax = rdr["Fax"].ToString();
}
}
}
}
}
// return customer object
return c;
}
catch (System.Exception ex)
{
return null;
}
}
Now again go back to the default.aspx page and prepare AJAX request using jquery. First include the jQuery library in the head section of the default.aspx page. (you can easily download the jquery file from internet)
<script type=”text/javascript” src=”Script/jquery-1.3.2.min.js”></script>
Now add the following javascript code
<script type=”text/javascript”>
// this method will be called when the page is loaded in the browser
$(document).ready(function()
{
//attach change event on asp dropdown list with id Customers.
$(‘#Customers’).change(function() {
// send ajax request.
$.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8″,
//pass parameter with the ajax request
data: “{ CustomerID: ‘” + $(‘#Customers’).val() + “‘}”,
//calling webservice
url: “FatchCustomers.asmx/GetCustomerDetailByID”,
//return type will be JSON
dataType: “json”,
//on success call this method.
success: BuildTable,
error:TransacionFailed
});
});
});
function TransacionFailed() {
$(‘#CustomerDetails’).empty();
$(‘#CustomerDetails’).append
(result.status + ‘ ‘ + result.statusText);
}
function BuildTable(msg) {
var table = ‘<table cellpadding=”5px” cellspacing=”5px” border=”1px”><thead><tr><th>Customer Id</th> <th>Customer Name</th> <th>Address</th><th>City</th> <th>Region</th><th>PostalCode</th><th>Country</th><th>Phone</th><th>Fax</th></thead><tbody>’;
//brows the returned JSON DATA
for (var cd in msg) {
var row = ‘<tr>’;
row += ‘<td>’ + msg[cd].CustomerID + ‘</td>’;
row += ‘<td>’ + msg[cd].CompanyName + ‘</td>’;
row += ‘<td>’ + msg[cd].Address + ‘</td>’;
row += ‘<td>’ + msg[cd].City + ‘</td>’;
row += ‘<td>’ + msg[cd].Region + ‘</td>’;
row += ‘<td>’ + msg[cd].PostalCode + ‘</td>’;
row += ‘<td>’ + msg[cd].Country + ‘</td>’;
row += ‘<td>’ + msg[cd].Phone + ‘</td>’;
row += ‘<td>’ + msg[cd].Fax + ‘</td>’;
row += ‘</tr>’;
table += row;
}
table += ‘</tbody></table>’;
$(‘#CustomerDetails’).html(table);
}
</script>
We are done. I always prefer jquery over asp.net ajax as it is far more easier and lite weight.