Click here to Skip to main content
15,896,453 members
Articles / Web Development / ASP.NET

XMLHTTPObject

Rate me:
Please Sign up or sign in to vote.
4.00/5 (4 votes)
30 Oct 2009CPOL2 min read 12.2K   10   1
ASP.NET and Ajax - using XmlHttpRequest

Introduction

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 functionality to ASP.NET Web Forms can be achieved by using jQuery. Please see this article. 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' selection 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:

JavaScript
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:

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

<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]">

</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 readyState property of the object for a value of 4 or complete, then to write the response to the empty div:

JavaScript
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:

JavaScript
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. Everything 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:

ASP.NET
<%@ 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:

C#
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("
");
    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() + "
");
      sb.Append(dr[4].ToString() + "
");
      sb.Append(dr[5].ToString() + "
");
      sb.Append(dr[6].ToString() + "
");
      sb.Append(dr[7].ToString() + "
");
      sb.Append(dr[8].ToString() + "
");
      sb.Append("Tel: " + dr[9].ToString() + "
");
    } 
    dr.Close();
    dr.Dispose();
    conn.Close();
    conn.Dispose();
    Response.Write(sb.ToString())
    Response.End();
  }
}

History

  • 30th October, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Zenta Private Ltd,Mumbai
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralGood Article Pin
Member 46278202-Nov-09 20:42
Member 46278202-Nov-09 20:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.