Click here to Skip to main content
15,879,095 members
Articles / Web Development / ASP.NET
Article

Working with ASP.NET AJAX

Rate me:
Please Sign up or sign in to vote.
4.47/5 (11 votes)
11 Nov 2011CPOL4 min read 58.1K   1.2K   19   19
This article describes how to work with ASP.NET AJAX
Sample Image - maximum width is 600 pixels

Introduction

The UpdatePanel control is one of the most important controls in the ASP.NET AJAX package. It enables you to create web pages with complex client behavior and a high level of interactivity and responsiveness.The UpdatePanel control can be used to perform partial updates of a web page. This means that the UpdatePanel control refreshes only a selected part of the web page instead of the entire web page. A page which contains a ScriptManager control and one or more UpdatePanel controls can automatically perform partial updates without having to write custom client script.

In this article, I have demonstrated the use of the UpdatePanel control with the help of a simple ASP.NET AJAX application which performs arithmetic calculations.

Background

ASP.NET AJAX is a technology that helps in developing ASP.NET applications that run with the speed of desktop applications. Following are some of the advantages of ASP.NET AJAX:

  • Better Efficiency - Since a major part of a web page is processed on the browser, the applications run faster.
  • UI Elements - We have access to various UI elements like progress indicators, tooltips, etc.
  • Partial Updates - Only the modified part of a web page is refreshed instead of the entire page.
  • Wide Browser Support - Since many browsers are supported, it helps in developing browser-independent applications.

Using the Code

ScriptManager and UpdatePanel controls

To create an ASP.NET AJAX application, we add a ScriptManager control in the Default.aspx file. Following is the markup code after adding the ScriptManager control:

Image 2

The ScriptManager control is used to add AJAX support to our application and is required on any page where AJAX functionality is required.

After the ScriptManager control, we add an UpdatePanel control as follows:

Image 3

The UpdatePanel control contains code for controls which must be partially updated. The code for the controls is written within the ContentTemplate child element of the UpdatePanel. The UpdatePanel control allows its content to be refreshed without causing a PostBack to the server.

All other markup code and code in the code behind files is the same as for any other ASP.NET application. Following is the code required for doing the calculations in the code behind file:

C#
protected void btnAdd_Click(object sender, EventArgs e)	// Adding Numbers
{
    try
    {
        int n1 = Convert.ToInt32(txtN1.Text);
        int n2 = Convert.ToInt32(txtN2.Text);
        int n3 = n1 + n2;
        lblResult.Text = "Addition is " + (n1 + n2);
    }
    catch (Exception ex)
    {
        lblResult.Text = ex.Message;
    }
}
protected void btnSubtract_Click(object sender, EventArgs e)	// Subtracting Numbers
{
    try
    {
        int n1 = Convert.ToInt32(txtN1.Text);
        int n2 = Convert.ToInt32(txtN2.Text);
        int n3 = n1 - n2;
        lblResult.Text = "Subtraction is " + (n1 - n2);
    }
    catch (Exception ex)
    {
        lblResult.Text = ex.Message;
    }
}
protected void btnMultiply_Click(object sender, EventArgs e)	// Multiplying Numbers
{
    try
    {
        int n1 = Convert.ToInt32(txtN1.Text);
        int n2 = Convert.ToInt32(txtN2.Text);
        int n3 = n1 + n2;
        lblResult.Text = "Multiplication is " + (n1 * n2);
    }
    catch (Exception ex)
    {
        lblResult.Text = ex.Message;
    }
}
protected void btnDivide_Click(object sender, EventArgs e)	// Dividing Numbers
{
    try
    {
        int n1 = Convert.ToInt32(txtN1.Text);
        int n2 = Convert.ToInt32(txtN2.Text);
        int n3 = n1 + n2;
        lblResult.Text = "Division is " + (n1 / n2);
    }
    catch (Exception ex)
    {
        lblResult.Text = ex.Message;
    }
}

Preserving State Information

When the application is executed now, it runs without causing a postback to the server. But by default, AJAX does not preserve state in the browser. As a result, you cannot use the Back and Forward buttons to move between states. To preserve state and allow users to navigate between different states, the history feature can be enabled. To enable the history feature, three more attributes are added to the ScriptManager control as follows:

Image 4
  • The EnableHistory attribute is used to turn the history feature on or off.
  • The OnNavigate attribute specifies the event method for the Navigate event of the ScriptManager.
  • The EnableSecureHistoryState attribute can be used to enable or disable secure URL. If this attribute is true, it displays a cryptic URL on the address bar. To view simple URL, this attribute must be turned off.

For the history state to work, the following changes are required in the code behind functions:

C#
protected void btnAdd_Click(object sender, EventArgs e)	// Adding Numbers
{
    try
    {
        int n1 = Convert.ToInt32(txtN1.Text);
        int n2 = Convert.ToInt32(txtN2.Text);
        int n3 = n1 + n2;
        lblResult.Text = "Addition is " + (n1 + n2);
        ScriptManager1.AddHistoryPoint("t1", txtN1.Text);	//Saving data in history
        ScriptManager1.AddHistoryPoint("t2", txtN2.Text);	//Saving data in history
        ScriptManager1.AddHistoryPoint("t3", lblResult.Text);	//Saving data in history
    }
    catch (Exception ex)
    {
        lblResult.Text = ex.Message;
    }
}

The following navigation function is required to restore the history state when the Back or Forward buttons are clicked:

C#
protected void Nav(object sender, HistoryEventArgs e)
{
    string t1 = e.State["t1"];	//Retrieving data from history
    string t2 = e.State["t2"];	//Retrieving data from history
    string t3 = e.State["t3"];	//Retrieving data from history
    txtN1.Text = t1;		//Displaying data on control
    txtN2.Text = t2;		//Displaying data on control
    lblResult.Text = t3;		//Displaying data on control
}

When the application is run now, the Back and Forward buttons can be used to view the different states.

UpdateProgress Control

The UpdateProgress control is used to show a Progress message if a function takes a long time to run. The UpdateProgress control is added to the markup code after the ScriptManager control as follows:

Image 5

The UpdateProgress control may not be displayed if a function is fast. So you can simulate a slow running function by adding the following statement to your function:

C#
System.Threading.Thread.sleep()
The modified function may look as follows:
C#
protected void btnAdd_Click(object sender, EventArgs e)	// Adding Numbers
{
    try
    {
        int n1 = Convert.ToInt32(txtN1.Text);
        int n2 = Convert.ToInt32(txtN2.Text);
        int n3 = n1 + n2;
        lblResult.Text = "Addition is " + (n1 + n2);
        ScriptManager1.AddHistoryPoint("t1", txtN1.Text);	//Saving data in history
        ScriptManager1.AddHistoryPoint("t2", txtN2.Text);	//Saving data in history
        ScriptManager1.AddHistoryPoint("t3", lblResult.Text);	//Saving data in history
        System.Threading.Thread.Sleep(1000);			// Simulating delay
    }
    catch (Exception ex)
    {
        lblResult.Text = ex.Message;
    }
}

The sleep() function is added only to demonstrate the use of the UpdateProgress control. It should not be generally added.

Points of Interest

I have created the above application using Visual Web Developer 2010 Express Edition. ASP.NET AJAX functionality is built-in to Visual Studio 2008 and Visual Studio 2010. I hope that this article will help people to understand the basic concepts of ASP.NET AJAX quickly and start developing faster web applications.

History

  • 11th November, 2011: Initial post

License

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


Written By
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with iFuture Technologies(India) as a Senior Faculty. I enjoy programming as a hobby. During my career I have seen the growth and decline of many technologies, many of them being my favorites like Flash, WPF, Windows Mobile Development. Few of my current favorites are Android, Xamarin and Python, though I also like traditional and evergreen languages like PHP, C#, Visual Basic and Java.

Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

 
QuestionNice article Pin
Member 124243658-Apr-16 12:55
Member 124243658-Apr-16 12:55 
Questionnice Pin
Jakub Jakubo18-Mar-16 5:07
Jakub Jakubo18-Mar-16 5:07 
Questionsuper Pin
Jakub Jakubo10-Mar-16 6:51
Jakub Jakubo10-Mar-16 6:51 
AnswerRe: super Pin
Azim Zahir5-Apr-16 3:17
Azim Zahir5-Apr-16 3:17 
Praisegreat Pin
Member 1219911510-Dec-15 6:10
Member 1219911510-Dec-15 6:10 
GeneralRe: great Pin
Azim Zahir9-Jan-16 23:46
Azim Zahir9-Jan-16 23:46 
Question.. Pin
Member 1123623415-Nov-14 4:33
Member 1123623415-Nov-14 4:33 
AnswerRe: .. Pin
Azim Zahir17-Nov-14 16:27
Azim Zahir17-Nov-14 16:27 
Questionalright Pin
Member 1116074917-Oct-14 0:12
Member 1116074917-Oct-14 0:12 
AnswerRe: alright Pin
Azim Zahir18-Oct-14 19:03
Azim Zahir18-Oct-14 19:03 
QuestionGreat Pin
rasikasamith16-Mar-14 3:26
rasikasamith16-Mar-14 3:26 
AnswerRe: Great Pin
Azim Zahir24-Mar-14 17:23
Azim Zahir24-Mar-14 17:23 
QuestionIf i code on Page load Pin
_Dhull 13-May-12 23:00
_Dhull 13-May-12 23:00 
AnswerRe: If i code on Page load Pin
Azim Zahir15-May-12 17:02
Azim Zahir15-May-12 17:02 
QuestionBe wary of using ASP.NET AJAX Pin
DaveRRR14-Nov-11 7:51
DaveRRR14-Nov-11 7:51 
AnswerRe: Be wary of using ASP.NET AJAX Pin
Azim Zahir14-Nov-11 18:29
Azim Zahir14-Nov-11 18:29 
AnswerRe: Be wary of using ASP.NET AJAX Pin
RLCornish3-Dec-11 11:55
RLCornish3-Dec-11 11:55 
GeneralRe: Be wary of using ASP.NET AJAX Pin
DaveRRR4-Dec-11 6:34
DaveRRR4-Dec-11 6:34 
GeneralMy vote of 3 Pin
evenbetter12-Nov-11 23:28
evenbetter12-Nov-11 23:28 

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.