Click here to Skip to main content
Click here to Skip to main content

Using AJAX in ASP.NET

, 23 Oct 2006
Rate this:
Please Sign up or sign in to vote.
This article shows you how to use AJAX to display a DataGrid dynamically.

Introduction

The latest buzz among web programmers is AJAX. Well, AJAX is nothing new, it has been around a while. It is nothing but remote scripting. AJAX is an acronym that stands for Asynchronous JavaScript and XML. You see AJAX used every where now. Google is an example. It is just the process of making an out - of - band call (e.g., not with the normal page POST / RELOAD cycle) to some external resource, getting back the result either synchronously or asynchronously, and updating the content of the page that initiated the call, usually using client-side HTML DOM methods.

In this article, I will show you how to use AJAX to display a DataGrid dynamically. I assume that you know how to use Visual Studio to create web pages and HTML forms. Actually, I was given this daunting task of converting existing applications in our company to use AJAX. So, I had to find a way to do it using the same page instead of creating a new page for every page which had to use AJAX.

The Steps

  1. Create the client page
  2. Add the JavaScript code
  3. Create the code remote .aspx page

Step 1

Open Visual Studio and create a new project. I used the name ajax. By default, Visual Studio creates a page Webapplication1.aspx.Note that I am using C# as the code-behind. Rename webapplication1.aspx to ajax.aspx.

Step 2

Drag and drop a DataGrid control from the web forms toolbox on to the page. Give the DataGrid an ID of dgView. Drag and drop an HTML text field from the HTML toolbox. Give it the name txtSearch. Drag and drop an HTML button from the HTML toolbox. Name it btnSubmit. In the HTML view, add the div tag which is used to show the populated data, any where after the form fields

<div id="datagrid"></div>

Step 3

And now comes the JavaScript code, the code is shown below. Don’t worry, I will explain how each function works. Add this code to the top of the page. Well, this code is the bread and butter of this script Smile | :) .

<script > 

var xmlHttp; 
var requestURL = ''http://localhost/ajax/ajax.aspx''; 
var is_ie = (navigator.userAgent.indexOf(''MSIE'') >= 0) ? 1 : 0; 
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||
                (navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
var is_netscape = (navigator.userAgent.indexOf(''Netscape'') >= 0) ? 1 : 0; 

function show_data(str) 
{ 
    var url = requestURL; 
    xmlHttp = GetXmlHttpObject(ChangeHandler); 
    var params = formData2QueryString(this.document.forms[0]); 
    url += "&query=str; 
    xmlHttp_Get(xmlHttp, url); 
} 


function ChangeHandler() 
{ 

    if (xmlHttp.readyState == 4 || 
        xmlHttp.readyState == ''complete''){ 
        //get the results from the callback 
        var str = xmlHttp.responseText; 

        //populate the innerHTML of the div with the results 
        document.getElementById(‘datagrid’).innerHTML = str; 
    } 
    else 
    { 
        document.getElementById(''datagrid'').innerHTML = 
           "<table><tr><td width=''28''><img " + 
           "src=''images/waiting6.gif'' ></td><td " + 
           "valign=''middle''><b>Your record is loading" + 
           " please wait</b></td></tr></table>"; 
    } 

} 

function xmlHttp_Get(xmlhttp, url) 
{ 
    xmlhttp.open(''GET'', url, true); 
    xmlhttp.send(null); 
} 

function GetXmlHttpObject(handler) { 
    var objXmlHttp = null;//Create the local xmlHTTP object instance 

    //Create the xmlHttp object depending on the browser 
    if (is_ie){ 
        //if not IE default to Msxml2 
        var strObjName = (is_ie5) ? ''Microsoft.XMLHTTP'' : 
                                    ''Msxml2.XMLHTTP''; 

        //Create the object 
        try{ 
            objXmlHttp = new ActiveXObject(strObjName); 
            objXmlHttp.onreadystatechange = handler; 
        } 
        catch(e){ 
            //Object creation error 
            alert(''Object cannot be created''); 
            return; 
        } 
    } 
    else if (is_opera){ 
        alert(''Opera browser''); 
        return; 
    } 
    else{ 
        // other browsers eg mozilla , netscape and safari 
        objXmlHttp = new XMLHttpRequest(); 
        objXmlHttp.onload = handler; 
        objXmlHttp.onerror = handler; 
    } 

    //Return the instantiated object 
    return objXmlHttp; 
} 
</script>
  • The function GetXmlHttpObject() checks the browser type and instantiates the XMLHttp object.
  • The function xmlHttp_Get uses the GET method to send requests to the remote script.
  • The function ChangeHandler() checks for the data processing, and if it receives the data, it populates the data on the client page.
  • The function show_data() is the function we call to get the page results. You have to add the OnClick event in the button onCLick="javascript:show_data('''')"

Be sure to update the requestURL variable with the path that you will be accessing the aspx file from.

The complete code listing looks like this

<%@ Page language="c#" Codebehind="ajax.aspx.cs" 
    AutoEventWireup="false" Inherits="ajax.ajax" %> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 
<HTML> 
<HEAD> 
<title>Reader</title> 
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> 
<meta name="CODE_LANGUAGE" Content="C#"> 
<meta name="vs_defaultClientScript" content="JavaScript"> 
<meta name="vs_targetSchema" 
   content="http://schemas.microsoft.com/intellisense/ie5"> 
<script> 
var xmlHttp; 
var requestURL = ''http://localhost/ajax/ajax.aspx''; 
var is_ie = (navigator.userAgent.indexOf(''MSIE'') >= 0) ? 1 : 0; 
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||
                (navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
var is_netscape = (navigator.userAgent.indexOf(''Netscape'') >= 0) ? 1 : 0; 

function show_data(str) 
{ 
    var url = requestURL; 
    xmlHttp = GetXmlHttpObject(ChangeHandler); 
    var params = formData2QueryString(this.document.forms[0]); 
    url += "&query="+this.document.forms[0].txtSearch.value; 
    xmlHttp_Get(xmlHttp, url); 
} 


function ChangeHandler() 
{ 

    if (xmlHttp.readyState == 4 || 
        xmlHttp.readyState == ''complete''){ 
        //get the results from the callback 
        var str = xmlHttp.responseText; 
    
        //populate the innerHTML of the div with the results 
        document.getElementById(''nameList'').innerHTML = str; 
    } 
    else 
    { 
        document.getElementById(''datagrid'').innerHTML = 
          "<table><tr><td width=''28''><img " + 
          "src=''images/waiting6.gif'' ></td><td " + 
          "valign=''middle''><b>Your record is loading " + 
          "please wait</b></td></tr></table>"; 
    } 

} 


function xmlHttp_Get(xmlhttp, url) 
{ 
    xmlhttp.open(''GET'', url, true); 
    xmlhttp.send(null); 
} 

function GetXmlHttpObject(handler) { 
    var objXmlHttp = null;
    //Create the local xmlHTTP object instance 

    //Create the xmlHttp object depending on the browser 
    if (is_ie){ 
        //if not IE default to Msxml2 
        var strObjName = (is_ie5) ? ''Microsoft.XMLHTTP'' : 
                                    ''Msxml2.XMLHTTP''; 

        //Create the object 
        try{ 
            objXmlHttp = new ActiveXObject(strObjName); 
            objXmlHttp.onreadystatechange = handler; 
        } 
        catch(e){ 
            //Object creation errore 
            alert(''Object cannot be created verify if ' + 
                  'Active scripting and activeX controls are enabled''); 
            return; 
        } 
    } 
    else if (is_opera){ 
        alert(''Opera browser''); 
        return; 
    } 
    else{ 
        // other browsers eg mozilla , netscape and safari 
        objXmlHttp = new XMLHttpRequest(); 
        objXmlHttp.onload = handler; 
        objXmlHttp.onerror = handler; 
    } 

    //Return the instantiated object 
    return objXmlHttp; 
} 
</script> 
</HEAD> 
<body MS_POSITIONING="GridLayout"> 
<form id="Form1" method="post" runat="server"> 
<asp:DataGrid id="dgView" 
    style="Z-INDEX: 101; LEFT: 144px; POSITION: absolute; TOP: 136px" 
    runat="server" Width="520px"></asp:DataGrid> 
<input type="text" name="txtSearch"> 
<input type="button" 
   onCLick="javascript:show_data('''')" name="btnSubmit"> 
</form> 
</body> 
</HTML>

Step 4

Adding the remote script. Go to the code behind of the aspx page. This is the what my code listing looks like:

using System; 
using System.Collections; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Web; 
using System.Web.SessionState; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.HtmlControls; 
using System.Data.SqlClient; 

namespace ajax 
{ 
    /// <summary> 
    /// Summary description for Reader. 
    /// </summary> 
    public class ajax : System.Web.UI.Page 
    { 
        protected System.Web.UI.WebControls.DataGrid dgView; 
        protected System.Web.UI.WebControls.Button Button1; 

        private void Page_Load(object sender, System.EventArgs e) 
        { 
            // Put user code to initialize the page here 
            if(Request.QueryString["query"] != null) 
            { 
                bind(); 
            } 
        } 


        private void bind() 
        { 
            //connection string to connect to the server 
            string ConnStr = "Server=servername;Database" + 
                             "=databasename;UID=UID;PWD=password;"; 
            SqlConnection sqlConn = new SqlConnection(ConnStr); 
            string query = "select * from table where text " + 
                   "like ''%"+Request.QueryString["query"]+"%''"; 
            SqlCommand sqlComm = new SqlCommand(query,sqlConn); 
            sqlComm.CommandType=CommandType.StoredProcedure; 
            sqlConn.Open(); 
            SqlDataReader sqlReader; 
            sqlReader = sqlComm.ExecuteReader(); 
            dgView.DataSource = sqlReader; 
            dgView.DataBind(); 
            System.IO.StringWriter oStringWriter = 
                     new System.IO.StringWriter(); 
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = 
               new System.Web.UI.HtmlTextWriter(oStringWriter); 
            dgView.RenderControl(oHtmlTextWriter); 
            Response.Write(oHtmlTextWriter); 

            Response.End(); 
        } 

#region Web Form Designer generated code 
        override protected void OnInit(EventArgs e) 
        { 
            // 
            // CODEGEN: This call is required by
            // the ASP.NET Web Form Designer. 
            // 
            InitializeComponent(); 
            base.OnInit(e); 
        } 

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor. 
        /// </summary> 
        private void InitializeComponent() 
        { 
            this.Load += new System.EventHandler(this.Page_Load); 
        } 
#endregion 
    } 
}

The code is simple, there is nothing complex in it. In the page load event, I am checking whether the query string query is sent with the URL. If it is sent, I will call the function bind. The function is self-explanatory. It calls the database, and I am populating it into the DataGrid. I use the RenderControl method to render the control, and send it as a response stream to the XmlHttp object, which in turn displays it on the browser in the DIV elements

I bet this is very useful. You can use the same page to do all the AJAX calls.

If you have done all the steps, run the page and insert something in the text field; if there is something in the database, it will return that to you as a DataGrid.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

DJKarakadu
Web Developer
United States United States
I work as a ASP.NET programmer and i love my job. I also run a .NET website called dotnetwatch c# tutorials

Comments and Discussions

 
GeneralSimple Code - Couple of Doubts Pinmemberraja_raman15-May-07 0:33 
GeneralIncomplete Code PinmemberMe the Lover27-Dec-06 4:16 
GeneralThreading error Pinmembertnsentil2-Nov-06 23:11 
Generalmissing code Pinmembermcgowand31-Oct-06 6:25 
GeneralIn complete code PinmemberAJFK31-Oct-06 5:29 
QuestionWhy Reinvent the Wheel? Pinmembercamainc30-Oct-06 15:18 
AnswerRe: Why Reinvent the Wheel? PinmemberJohn Storer II31-Oct-06 2:47 
GeneralNice tehnique Pinmemberjeremykirkup23-Oct-06 7:28 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150414.1 | Last Updated 23 Oct 2006
Article Copyright 2006 by DJKarakadu
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid