Simple Ajax Request

1

The Simple AjaxRequest is a very easy ASP.Net tutorial by CMSN Software. In this tutorial you can get a clear idea about basic steps to create Ajax request using ASP.Net. Before we begin with the tutorial, let's discuss about technologies first. There are basically three technologies have been used to fulfill same task that is read a text file and show the file content without doing a post back.

you can get a better understanding on how to use
  • JavaScript
  • ASP.NET Ajax
  • jQuery
By going through this article you can decide what technology you will use for your next application.
This sample shows you how to load text file content using JavaScript through Ajax request.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JavaScriptSample._Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Simple Ajax Request</title>
 
    <script type="text/javascript">
        function loadContent()
        {
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                this.xmlhttp = new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                try
                {
                    this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e1)
                {
                    try
                    {// older version of Msxml
                        this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e2)
                    {
                        this.xmlhttp = null;
                    }
                }
            }
            xmlhttp.onreadystatechange = function()
            {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                {// Display response when success.
                    document.getElementById("SimpleAjaxResponse").innerHTML = xmlhttp.responseText;
                }
            }
            this.xmlhttp.open("GET""AjaxResponse.txt"true);
            this.xmlhttp.send();
        }
    </script>
 
</head>
<body>
    <form id="SimpleAjaxRequestForm" runat="server">
    <div>
        <asp:Button ID="SimpleAjaxRequestButton" runat="server" Text="Request" />
        <div id="SimpleAjaxResponse" runat="server">
        </div>
    </div>
    </form>
</body>
</html>

As you can see XMLHttpRequest object is the main actor of the above tutorial. This is the technology used in all modern browsers to exchange data with a server to update parts of a web page without reloading the whole page. But Old versions of Internet Explorer (IE5 and IE6) uses an ActiveXObject to do the same task.

To send a request to a server, we use the open(method,url,async) and send(string) methods of the XMLHttpRequest object.

The onreadystatechange event is triggered every time when XMLHttpRequest readyState changes.When readyState is 4 and status is 200, the response is ready and you can access  that using responseText or responseXML property of the XMLHttpRequest object.

//-----------------------------------------------------------------------
// <copyright file="Default.aspx.cs" company="CMSN Software">
//    Copyright © 2010  CMSN Software
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see http://www.gnu.org/licenses.
// </copyright>
//-----------------------------------------------------------------------
        
namespace JavaScriptSample
{
    using System;
    using System.Diagnostics.CodeAnalysis;
 
    /// <summary>
    /// Code behind of the Default.aspx
    /// </summary>
    [SuppressMessage("Microsoft.Naming""CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Generatd By IDE")]
    public partial class _Default : System.Web.UI.Page
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.SimpleAjaxRequestButton.Attributes.Add("onclick""loadContent(); return false;");
        }
    }
}

The only thing we have done in the code behind file is, just add onclick attribute to the button.

This sample shows you how to load text file content using ASP.NET through Ajax request.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MicrosoftAjaxSample._Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Simple Ajax Request</title>
</head>
<body>
    <form id="SimpleAjaxRequestForm" runat="server">
    <div>
        <asp:ScriptManager ID="SimpleAjaxRequestScriptManager" runat="server">
        </asp:ScriptManager>
        <asp:Button ID="SimpleAjaxRequestButton" runat="server" Text="Request" 
            onclick="SimpleAjaxRequestButton_Click" />
        <asp:UpdatePanel ID="SimpleAjaxRequestUpdatePanel" runat="server">
            <ContentTemplate>
                <div id="SimpleAjaxResponse" runat="server">
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

In this sample code we used ScriptManager & UpdatePanel to do the whole thing. The ScriptManager makes sure that the required ASP.NET AJAX files are included and that AJAX support is added to the page.The UpdatePanel allows you to wrap markup which you would like to allow to be partially updated(updated without causing a real post back to the server).

//-----------------------------------------------------------------------
// <copyright file="Default.aspx.cs" company="CMSN Software">
//    Copyright © 2010  CMSN Software
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see http://www.gnu.org/licenses.
// </copyright>
//-----------------------------------------------------------------------        
namespace MicrosoftAjaxSample
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Text;
 
    /// <summary>
    /// Code behind of the Default.aspx
    /// </summary>
    [SuppressMessage("Microsoft.Naming""CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Generatd By IDE")]
    public partial class _Default : System.Web.UI.Page
    {
        /// <summary>
        /// File to read via ajax
        /// </summary>
        private const string FileToLoad = "AjaxResponse.txt";
 
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
        }
 
        /// <summary>
        /// Handles the Click event of the SimpleAjaxRequestButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void SimpleAjaxRequestButton_Click(object sender, EventArgs e)
        {
            // create reader & open file
            using (StreamReader fileContent = new StreamReader(FileToLoad))
            {
                StringBuilder content = null;
                while (fileContent.ReadLine() != null)
                {
                    content.Append(fileContent.ReadLine());
                }
 
                this.SimpleAjaxResponse.InnerHtml = content.ToString();
            }
        }
    }
}

Nothing special in the code behind file. we just read the content of the text file using C# code. The UpdatePanel handled the rest of the things.

This sample shows you how to load text file content using jQuery through Ajax request.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JquerySample._Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Simple Ajax Request</title>
 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
 
    <script type="text/javascript">
        $(document).ready(function()
        {
            $("#SimpleAjaxRequestButton").click(function()
            {
                $.ajax({
                    type: "GET",
                    url: "AjaxResponse.txt",
                    success: function(html)
                    {
                        $("#SimpleAjaxResponse").html(html);
                    }
 
                });
                return false;
            });
        });
    </script>
 
</head>
<body>
    <form id="SimpleAjaxRequestForm" runat="server">
    <div>
        <asp:Button ID="SimpleAjaxRequestButton" runat="server" Text="Request" />
        <div id="SimpleAjaxResponse" runat="server">
        </div>
    </div>
    </form>
</body>
</html>

In this sample we don't have much more lines to explain. Because jQuery handled most of the things. .ready function is used to determine when page is load. JavaScript provides the .load event for executing code when a page is rendered. But it does not get triggered until all assets such as images have been completely received. jQuery .ready execute after the DOM is ready.

When DOM is ready we bind the .click event for the button. Inside button click event we call the .ajax api to load the text file content and when it success result will display.

Download tutorial

1 comments:

Post a Comment