2 Ways to Implement AJAX in ASP.Net Application

This article shows two ways to implement AJAX in your application. If you are totally new to AJAX or this is the first time you have heard the term then this article is not suitable for you. Don't be disappointed my dear, there was a day when I was like you. OK, let's return to our discussion.

If you are still reading then that means you understand the basic concepts of AJAX and are interested in learning how to implement AJAX in an ASP.NET application. In this article, rather than discussing the basic concepts of AJAX we will go directly through some examples.

What are the ways?

My first way is to implement AJAX using Update Panel in ASP.NET and the second way is to implement AJAX using jQuery. If you don't have a basic idea of jQuery then I suggest you read it here then proceed with this article. Let's start with an example.

Implement AJAX using Update Panel

If you are an ASP.NET developer then you probably are aware of the AJAX Extension tab in Visual Studio (2010 or higher generally) Toolbox and the tab has a few very useful tools to implement AJAX in a web application. In the first example we will implement AJAX using UpdatePanel and ScriptManager . Both tools are available in the same tab of the Toolbox.

UpdatePanel

Let's learn a few lines about Update Panel. It's nothing but a region that will be updated in asynchronous operations. And this is the beauty of AJAX. The contents of the UpdatePanel will be updated and the outside content will remain the same.

ScriptManager

This is the hero of AJAX implementation in ASP.NET. Before writing any code related to ajax ypu need to put a ScriptManager tag in the aspx page.

Let's see one example in action.

The following will print the time within an Update Panel:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

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

    <div>

    //Script manager tag is here

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

    </asp:ScriptManager>

   

    // Code outside of Update panel

    Time at Load Time <%= DateTime.Now.ToLongTimeString() %>.

   

    // code inside Update panel

    <asp:UpdatePanel ID="UpdatePanel1"

         runat="server" UpdateMode="Conditional">

    <ContentTemplate>

    Latest Time by refresh <%= DateTime.Now.ToLongTimeString() %>.

    <br /><asp:Button Text="Refresh Time" ID="Button1"

        runat="server"/>

    </ContentTemplate>

    </asp:UpdatePanel> 

 

    </div>

   

    </form>

</body>

</html>

Here is the output window:

Ajax1.jpg

If you try this example in your Development environment and run it then you can find the second date display is updated after each press of the button, because it's within the update panel. But the first label is (First Time display) as it is. OK, you are saying , "this is a very simple example and it's not at all useful in project development". Then I will show you something more useful than this. Let's make a little database operation by AJAX technique.

Fetch Data from Database using AJAX

Here I would like to show how to fetch data from a database and display it within a Grid using AJAX. The basic concept or implementation is the same. I will keep a few controls within the Update Panel and that's all.

Here is my aspx page:
 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>           

<body>

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

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

    </asp:ScriptManager>

   

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

        <ContentTemplate>

            <asp:DropDownList ID="DDLAjax" runat="server" Height="16px" Width="117px">

            </asp:DropDownList>

            <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Show"

                Width="95px" />

            <br />

            <asp:GridView ID="GridView1" runat="server">

            </asp:GridView>

        </ContentTemplate>

    </asp:UpdatePanel>

    </form>

</body>

</html>
 

If you observe the content of my aspx page then you will discover that I have kept one drop down list, one button and one GridView within the UpdatePanel. And our hero (read ScriptManager) is just in the previous line of update panel. Now it's time to observe C# code for the same aspx page.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

namespace YahooProject

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                this.DDLAjax.Items.Add("first");

                this.DDLAjax.Items.Add("second");

            }

        }

 

        protected void Button1_Click(object sender, EventArgs e)

        {

            SqlConnection con = new SqlConnection();

     con.ConnectionString = "Data Source=SERVERNAME;Initial atalog=DATABALENAME;Integrated Security=True";

            con.Open();

            SqlCommand cmd = null;

 

            if (this.DDLAjax.SelectedItem.Text == "first")

            {

                cmd = new SqlCommand("select * from first",con);

            }

            if (this.DDLAjax.SelectedItem.Text == "second")

            {

                cmd = new SqlCommand("select * from second", con);

            }

            this.GridView1.DataSource = cmd.ExecuteReader();

            this.GridView1.DataBind();

        }

    }

}

Hey; no rocket science here. The user will choose the table name by selecting it from the drop down list and after clicking the button the data from the relevant table will be fetched and bound with the Grid View. And we need to keep in mind only the component within the update panel (here GridView basically) will be updated. Yes, after testing I woite this article. The following is the evidence (Ha Ha..):

Ajax2.jpg

OK, I hope you got the basic idea of UpdatePanel to implement AJAX. Let's start with the second approach.

Implement AJAX using jQuery Method

I hope you have a basic understanding of jQuery and are familiar with a few methods of it. One beautiful method of jQuery is the ajax method. Using this method we can implement AJAX in ASP.NET . Basically we will call one service method using the jQuery AJAX method. Let's see our young age's "Hello world" program in action.

Here is my content of the .aspx page.
 

<!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></title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">

    </script>

 

    <script type = "text/javascript">

        function DisplayMessageCall() {

            var pageUrl = '<%=ResolveUrl("~/AjaxServeice.asmx")%>'

            $.ajax({

                type: "POST",

                url: pageUrl + "/HelloWorld",

                contentType: "application/json; charset=utf-8",

                dataType: "json",

                success: OnSuccessCall,

                error: OnErrorCall

            });

        }

        function OnSuccessCall(response) {

            $('#<%=lblOutput.ClientID%>').html(response.d);

        }

        function OnErrorCall(response) {

            alert(response.status + " " + response.statusText);

        }

</script>

 

</head>

<body>

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

    <div>

    <asp:Button ID="btnGetMsg" runat="server" Text="Click Me" OnClientClick="DisplayMessageCall();return false;" /><br />

    <asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>

    </div>

    </form>

</body>

</html>


In the head section of the HTML element you can see one function that I have implemented to an AJAX call in JavaScript.

And the following is the body of the ajax() method:

$.ajax({
                type: "POST",
    url: pageUrl + "/HelloWorld",
   
contentType: "application/json; charset=utf-8",
   
dataType: "json",
    success: OnSuccessCall,
    error: OnErrorCall
});

You can see a few parameters are needed for AJAX to call using the jQuery ajax() method. My URL parameter is in the second and it's the defined location of the actual function from where the data will come. Here "HelloWorld" is the function name. And this function is located within the AjaxServeice.asmx service application page.

var pageUrl = '<%=ResolveUrl("~/AjaxServeice.asmx")%>'

I have defined the page location like this.

OK, let's concentrate on the service function from where the data will come in the ajax() method and in the following it is.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

 

namespace YahooProject

{

   

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [System.ComponentModel.ToolboxItem(false)]

    [System.Web.Script.Services.ScriptService] // Don't forget to uncomment it.

    public class AjaxServeice : System.Web.Services.WebService

    {

 

        [WebMethod]

        public string HelloWorld()

        {

            return "Hello World";

        }

    }

}

Hmm, again a simple example, but you can implement the HelloWorld function as complex as possible with your database access mechanism code or business logic.

Note: Don't forget to uncomment the following line above your class name.

[System.Web.Script.Services.ScriptService]

Here is the output of the above example:

Ajax3.jpg

Hope you understood those two approaches to implement AJAX in ASP.NET applications. For any difficulty or comments please leave a comment.
 

Up Next
    Ebook Download
    View all
    Learn
    View all