ASP.NET and Ajax - using XmlHttpRequest

If you are not interested in using the ASP.NET AJAX library offered for ASP.NET, but would like to feature small amounts of AJAX functionality on your pages, you can do this easily with some javascript and a receptive page.

UPDATE: A much simpler way to add small doses of AJAX fuctionality to ASP.NET Web Forms can be achieved by using jQuery. Please see this article: http://www.mikesdotnetting.com/Article/104/Many-ways-to-communicate-with-your-database-using-jQuery-AJAX-and-ASP.NET

I only use AJAX in small doses on web sites - mainly to improve the user-experience. Typical instances will involve retrieving a full record based on a users sleection in a drop down list. I don't want to perform a full page postback, so I get the javascript xmlhttpserver object to do it for me behind the scenes. Here's an example that fetches the address details for a Northwind Traders customer.

First, a generic function to instantiate an instance of xmlhttprequest or xmlhttp, depending on the browser:

  function GetXmlHttpObject(handler)
  { 
  var objXmlHttp=null
  if (navigator.userAgent.indexOf("MSIE")>=0)
  { 
  var strName="Msxml2.XMLHTTP"
  if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
  {
  strName="Microsoft.XMLHTTP"
  } 
  try
  { 
  objXmlHttp=new ActiveXObject(strName)
  objXmlHttp.onreadystatechange=handler 
  return objXmlHttp
  } 
  catch(e)
  { 
  alert("Error. Scripting for ActiveX might be disabled") 
  return 
  } 
  } 
  if (navigator.userAgent.indexOf("Mozilla")>=0)
  {
  objXmlHttp=new XMLHttpRequest()
  objXmlHttp.onload=handler
  objXmlHttp.onerror=handler 
  return objXmlHttp
  }
  } 

Now, a simple dropdownlist populated by a SqlDataSource control that fetches the CustomerID and Customer Name. Note the empty div, CustomerDetails below the dropdownlist:

<div>
<asp:DropDownList ID="DropDownList1" 
runat="server" 
DataSourceID="SqlDataSource1"
DataTextField="CompanyName" 
DataValueField="CustomerID">
</asp:DropDownList>

<asp:SqlDataSource 
ID="SqlDataSource1" 
runat="server" 
ConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
DataSourceMode="DataReader" 
ProviderName="System.Data.OleDb"
SelectCommand="SELECT [CustomerID], [CompanyName] FROM [Customers]">
</asp:SqlDataSource>

</div>
<div id="CustomerDetails"></div>

Two more javascript functions are needed. One to fire the GetXmlHttpObject method, and denote the page to send a request to, and one to handle the response by checking the readtState property of the object for a value of 4 or complete, then to write the reponse to the empty div:

  function GetCustomer(id)
  { 
  var url="FetchCustomer.aspx?CustomerID=" + id ;
  xmlHttp=GetXmlHttpObject(stateChanged);
  xmlHttp.open("GET", url , true);
  xmlHttp.send(null);
  } 
  
  
  function stateChanged() 
  { 
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  {
  document.getElementById('CustomerDetails').innerHTML=xmlHttp.responseText;
  }
  } 

So now we have a page that gets called by xmlhttp (FetchCustomer.aspx) and we have a value to pass to the querystring for the page. So the next thing to do is to add an event handler to the DropDownList that will fire the GetCustomer() event and pass a CustomerID value:

  if (!Page.IsPostBack)
  {
  DropDownList1.DataBind();
  DropDownList1.Items.Insert(0, "");
  }

  DropDownList1.Attributes["onChange"] = "GetCustomer(this.value);";
  HttpResponse myHttpResponse = Response;
  HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
  DropDownList1.Attributes.AddAttributes(myHtmlTextWriter);

And finally, the code for the FetchCustomer.aspx page. Everyting has been removed from the .aspx file except the first line. We don't want DocTypes or default <form> tags disturbing the piece of html to be emitted in the response:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="FetchCustomer.aspx.cs" Inherits="FetchCustomer" %>

And the code-behind makes doubly sure by calling Response.Clear() before querying the database and emitting the resulting data as html:

using System;
using System.Data;
using System.Data.OleDb;
using System.Text;

public partial class FetchCustomer : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    Response.Clear();
    StringBuilder sb = new StringBuilder();
    sb.Append("<br />");
    string provider = "Provider=Microsoft.Jet.OLEDB.4.0;";
    string db = "Data Source=|DataDirectory|Northwind.mdb";
    string connstr = provider + db;
    string query = "SELECT * FROM Customers WHERE CustomerID = ?";
    OleDbConnection conn = new OleDbConnection(connstr);
    OleDbCommand cmd = new OleDbCommand(query, conn);
    cmd.Parameters.AddWithValue("", Request.QueryString["CustomerID"]);
    conn.Open();
    OleDbDataReader dr = cmd.ExecuteReader();
    while(dr.Read())
    {
      sb.Append(dr[1].ToString() + "<br />");
      sb.Append(dr[4].ToString() + "<br />");
      sb.Append(dr[5].ToString() + "<br />");
      sb.Append(dr[6].ToString() + "<br />");
      sb.Append(dr[7].ToString() + "<br />");
      sb.Append(dr[8].ToString() + "<br />");
      sb.Append("Tel: " + dr[9].ToString() + "<br />");
    } 
    dr.Close();
    dr.Dispose();
    conn.Close();
    conn.Dispose();
    Response.Write(sb.ToString())
    Response.End();
  }
}

Date Posted:
Last Updated:
Posted by:
Total Views to date: 73743

9 Comments

- Raghav Khunger

Hi,Mikes I am Raghav Khunger Star Level Member In Asp.net community .I found Ur this Article Great FOr XmlHttp Request Explanation.How ever I was facing one problem in the above code at document.getElementById('CustomerDetails').innerHTML=xmlHttp.responseText;
In IE At this point it was again and agin showing htmlfile: Unknown runtime error .There for After So many trials I found a solution .I added Response.End(); at the last of FetchCustomer.aspx.cs Thanks So much

- Mike

Thanks, Raghav. I've amended the code to cater for IE.

- Remy

This is a nice example.
Would you make the entire code available for download...
I'm struggling with the fact that .aspx only has 2 lines of code:
%@ Page Language="C#" AutoEventWireup="true"
CodeFile="FetchCustomer.aspx.cs" Inherits="FetchCustomer" %>


and where to put the javascript code and presentation code (dropdown/etc you have listed.

- Mike

Remy - all the code you need is in the article. FetchCustomer.aspx only has two lines because you don't want anything to interfere with the Response - just as it explains in the article. This article is quite old - there are other ways of using AJAX in ASP.NET, such as using jQuery with Web Services. Have a look at a more recent article here: http://www.mikesdotnetting.com/Article/96/Handling-JSON-Arrays-returned-from-ASP.NET-Web-Services-with-jQuery

- Marc

Hello, I am very very new to AJAX, and here is where I am stuck...

I understand how to manipulate pages with JavaScript and DOM, and even how to send xmlHTTPrequest, but I have no clue how to access that request (specifically the information I put in it) from my server-side C# code. I can't seem to find a resource that explains this. PLEASE help!

- Mike

- prashant singh

Hi Mike
I am regular reader of your blogs on .net and I have to say one thing to you.
"You are the person who always try to establish a Milestone on other's way"

Thank's a Lot for your dedication to the .net
I have a Query to U
Can jQuery-AJAX-and-ASP.NET Web Services help us to upload file?

- Syed Fasih

Full Marks!!!! I have rated 5 this article. Wonderfull Effort!

- skatedotnet

thank you very much!

Recent Comments

Gayan 7/3/2015 6:20 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
Great Article thanks...

Semil 7/1/2015 7:03 AM
In response to iTextSharp - Drawing shapes and Graphics
I have created a rectangle using above methode. Now I want to add a text in the center of this How I...

Satyabrata Mohapatra 6/30/2015 6:12 PM
In response to Reading Excel Files Without Saving To Disk In ASP.NET
Ahh.....this is awesome. Happy to see after a long time you wrote a article on web form :D...

Marty 6/30/2015 7:16 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, you're the Man! Another great article. So incredibly helpful. I'm definitely going to buy your...

Rohan 6/30/2015 5:32 AM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Very good and helpful tutorial. Thanks. Just wanted to know what would be the max file size limit we...

Fernando 6/30/2015 1:59 AM
In response to Programmatically accessing data from DataSource controls
What if I want to pass parameters natively using the DataSourceSelectArguments object, instead of be...

pankaj 6/29/2015 3:13 PM
In response to How to retain carriage returns or line breaks in an ASP.NET web page
very nice i'm use this in my code thank you.... ...

Mike 6/29/2015 2:22 AM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
This is the first example that I have found that works....

Marty 6/28/2015 4:57 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, what if I don't want to render back the text to the browser, but I want to send it some other...

Mike 6/27/2015 4:00 PM
In response to Migrating Classic ASP To ASP.NET Razor Web Pages Part One- Razor Syntax And Visual Basic
have you used any of the code converters to convert classic asp to c#? If so, which one do you have...