CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Implementing AJAX Enabled Applications in ASP.Net

By Satheesh babu
Posted On Aug 07,2008
Article Rating:
Be first to rate
this article.
No of Comments: 2
Category: ASP.Net AJAX
Print this article.

Implementing AJAX Enabled Applications in ASP.Net

Introduction

AJAX stands for Asynchronous JavaScript and XML. AJAX can be used for asynchronous request/response processing in a web application without refreshing whole page in the browser. In Web application, the entire page will be refreshed for a request given to the web server. With Ajax, it is possible to refresh a portion of a page or post a portion of a page to server to get response. The result of the response will be posted in the browser without refreshing other content of a page. In short, Ajax can be used to develop rich internet applications. AJAX application uses JavaScript to call a server side function and underlying communication is done in XML. Ajax application will communicate with the server with the help of XMLHttpRequest object of the browser. To implement AJAX enabled application, Microsoft released a framework called ASP.Net AJAX(Previously called ATLAS).

 

This article will help us understand the basics of implementing AJAX enabled application in ASP.Net.

 

AJAX Implementation

Ø       Initially, if we need to implement an AJAX application we need to use JavaScript and ActiveX XMLHttpRequest object (IE) or XMLHttpRequest object in other browsers.

Ø       Michael Schwarz introduced an AJAX.Net library which can be used to build AJAX application in ASP.Net.

Ø       Later Microsoft released its own framework for implementing AJAX application called ASP.Net AJAX (Previously named ATLAS) for ASP.Net 2.0 and ASP.Net 3.5.

Note:

For ASP.Net 2.0, the ASP.Net AJAX framework is available as an add-on for free. AJAX functionality is integrated in ASP.NET 3.5 and does not require any additional downloads.

 

Before exploring the ASP.Net Ajax framework, we will understand how a simple AJAX application can be implemented using JavaScript & XMLHttpRequest object and using AJAX.Net library. This will help us understand how ASP.Net AJAX framework can be used to implement rich internet application more efficiently and easily.

 

For a simple understanding, we will implement a simple application which gets input from 2 textboxes and provides the sum by calling a server side function. We will have 2 textboxes, TextBox1 and TextBox2. When we click on the ADD button, it will call a server side function to add and populate the output in a textbox called TextBox3.

 

AJAX with JavaScript and XMLHttpRequest object

<script language="javascript">

 var XmlHttp;

function callserver()

{

   

    //Creating object of XMLHTTP in IE

       try

       {

              XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

       }

       catch(e)

       {

              try

              {

                     XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

              }

              catch(oc)

              {

                     XmlHttp = null;

              }

       }

       //Creating object of XMLHTTP in Mozilla and Safari

       if(!XmlHttp && typeof XMLHttpRequest != "undefined")

       {

              XmlHttp = new XMLHttpRequest();

       }

    var requestUrl = "AjaxFnForm.aspx?no1="+document.getElementById("TextBox1").value+"&no2="+document.getElementById("TextBox2").value+"";

      if(XmlHttp)

           {

                  XmlHttp.onreadystatechange = HandleResponse;

             

                  //Initializes the request object with GET METHOD

                  //Request URL and sets the request as asynchronous.

                  XmlHttp.open("GET", requestUrl,  true);

             

                  //Sends the request to server

                  XmlHttp.send(null);          

           }

}

function HandleResponse()

{

       // To make sure receiving response data from server is completed

       if(XmlHttp.readyState == 4)

       {

              // To make sure valid response is received from the server, 200 means response received is OK

              if(XmlHttp.status == 200)

              {     

              var ob=XmlHttp.responseText;

              //alert(ob); 

              var t=document.getElementById("TextBox3");

              t.value=ob;

              }

              else

              {

                     alert("No Response from Server" );

              }

       }

</script>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

<input id="Button1" type="button" value="ADD" onclick="callserver()"/>

 

Since, XMLHttpRequest object is an activex control in IE we are instantiating as ActiveXObject("Microsoft.XMLHTTP"). Once the server execution is completed, it will call HandleResponse() method which is attached to the event handler onreadystatechange of XMLHttpRequest. The Server request is given as a GET method and hence, server side function is an aspx page which adds the 2 number by getting it as query string.

The server side aspx page that will perform the summation is,

AjaxFnForm.aspx

protected void Page_Load(object sender, EventArgs e)

    {

        string n1 = Request.QueryString["no1"];

        string n2 = Request.QueryString["no2"];

        int sum = 0;

        if(n1 != "" & n2 != "")

         sum = int.Parse(n1) + int.Parse(n2);

        Response.Write(sum.ToString());

        Response.End();       

    }

Execute the page to see AJAX using Jscript in action.

The above code uses GET method.

The same can be implemented using POST method also. The below code does that.

 

<script language="javascript">

var XmlHttp;

function callserver()

{

   

    //Creating object of XMLHTTP in IE

       try

       {

              XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");

       }

       catch(e)

       {

              try

              {

                     XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

              }

              catch(oc)

              {

                     XmlHttp = null;

              }

       }

       //Creating object of XMLHTTP in Mozilla and Safari

       if(!XmlHttp && typeof XMLHttpRequest != "undefined")

       {

              XmlHttp = new XMLHttpRequest();

       }

    var requestUrl = "AjaxFnForm.aspx";

    var parameter = "no1="+document.getElementById("TextBox1").value+"&no2="+document.getElementById("TextBox2").value+"";

    if(XmlHttp)

           {

              XmlHttp.onreadystatechange = HandleResponse;                 

                  //Initializes the request object with POST METHOD,

                  //Request URL and sets the request as asynchronous.

            XmlHttp.open("POST", requestUrl,  true);

            XmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

            XmlHttp.setRequestHeader("Content-length", parameter.length);

            XmlHttp.setRequestHeader("Connection", "close");

 

                  //Sends the request to server

                  XmlHttp.send(parameter);            

           }

}

function HandleResponse()

{

       // To make sure receiving response data from server is completed

       if(XmlHttp.readyState == 4)

       {

              // To make sure valid response is received from the server, 200 means response received is OK

              if(XmlHttp.status == 200)

              {     

              var ob=XmlHttp.responseText;

              //alert(ob); 

              var t=document.getElementById("TextBox3");

              t.value=ob;

              }

              else

              {

                     alert("No Response from Server" );

              }

       }

}

</script>

 




AJAX using AJAX.Net

Download the AJAX.Net library from the Michael’s website . For ASP.Net 2.0, add reference to AjaxPro.2.dll from the downloaded library.

 

Add the following Web.Config setting,

    <httpHandlers>

      <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>

    </httpHandlers>

 

We need to register the CodeBehind class for the AJAX support. The following code will do this,

    protected void Page_Load(object sender, EventArgs e)

    {

        //register the page for ajax

        AjaxPro.Utility.RegisterTypeForAjax(typeof(AjaxdotNet));

    }

To get the sum of 2 numbers, we need to write method in codebehind class. This method should be decorated with [AjaxPro.AjaxMethod] attribute for the framework to understand it is the server method that will be called by the client.

    [AjaxPro.AjaxMethod]

    public string GetSum(int no1,int no2)

    {

        int sum = no1 + no2;

        return sum.ToString();

    }

 

We can call this server method from the JavaScript similar to calling a method in a .Net object.

 

   <script language="javascript">

    function callserver()

    {

        document.getElementById("TextBox3").value = AjaxdotNet.GetSum(document.getElementById("TextBox1").value,document.getElementById("TextBox2").value).value;

    }

   

    </script>

 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

 <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

 <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

 <input id="Button1" type="button" value="ADD" onclick="callserver()"/>

 

Execute the page to see AJAX.Net in action.

 

Using ASP.Net AJAX

For ASP.Net 2.0, ASP.Net AJAX is available as ASP.NET AJAX Extensions 1.0 for free download. For ASP.Net 3.5, AJAX functionality is integrated in ASP.NET 3.5 and does not require any additional downloads.

Download and install the library on your development machine to start developing ASP.Net AJAX applications.

To implement our sample application,

 Open Visual Studio 2005 and click New Website. After ASP.Net AJAX installation, a new Visual Studio template will be installed called “ASP.Net AJAX-Enabled Web Site”. Refer the below figure,

 

There will be a new tab in the toolbox of the Visual Studio 2005 called Ajax Extensions which has ASP.Net AJAX controls. Refer the below figure.

 

Before implementing the sample application, we will understand the basics of 2 new controls called ScriptManager and UpdatePanel which makes AJAX possible.

By default, the webpage will have an object called ScriptManager. This is the control that manages and registers the client script for aspx pages. By using UpdatePanel control, it is possible to update a portion of page or post a portion of page to the server. In other words, the controls inside UpdatePanel control will become AJAX enabled control which does not refreshes the browser for the postback to the server. We will see more about these controls in future articles. We will now implement our sample applications.

Steps

1.      Drag an UpdatePanel Control.

2.      Drag 3 textboxes and a button control inside the UpdatePanel control.

3.      In the button click event, perform the sum of 2 numbers entered in the textbox and populate it to the third textbox.

   protected void btnSum_Click(object sender, EventArgs e)

    {

        int sum =0;

        if(TextBox1.Text != "" && TextBox2.Text !="")

            sum = int.Parse(TextBox1.Text) + int.Parse(TextBox2.Text);

        TextBox3.Text = sum.ToString();

    }

ASPX

    <form id="form1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server" />

        <div>

            <asp:UpdatePanel ID="UpdatePanel1" runat="server">

                <ContentTemplate>                   

                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

                    <asp:Button ID="btnSum" runat="server" Text="SUM" OnClick="btnSum_Click" />

                </ContentTemplate>

            </asp:UpdatePanel>

           </div>

    </form>

It’s all done, execute the page and see it in action.

 

OUTPUT

 

Downloads

Download Source

 

Conclusion

This article will help us understand the basics of AJAX in a better way. Since, we have implemented the sample application in traditional Jscript way and AJAX.Net framework, it is now possible to understand the how simple we can implement AJAX enabled application using ASP.Net AJAX framework. The other 2 approaches use more steps and more code to implement an AJAX application when we compare ASP.Net AJAX framework. With the introduction of ASP.Net AJAX framework, it is now possible to implement AJAX enabled application faster and more efficiently. Moving forward, we will learn the how to implement ASP.Net AJAX applications with more features in future articles. Download the code attached with this article and see it in action.

Happy Coding!!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
implementing ajax
thank you .......... its really very good and very helful for the new students ....
nouad
good