Click here to Skip to main content
11,647,748 members (70,295 online)
Click here to Skip to main content

Working with ASP.NET AJAX

, 11 Nov 2011 CPOL 26.8K 1.1K 19
Rate this:
Please Sign up or sign in to vote.
This article describes how to work with ASP.NET AJAX
Sample Image - maximum width is 600 pixels

Introduction

The UpdatePanelcontrol 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 UpdatePanelcontrol can be used to perform partial updates of a web page. This means that the UpdatePanelcontrol refreshes only a selected part of the web page instead of the entire web page. A page which contains a ScriptManagercontrol and one or more UpdatePanelcontrols can automatically perform partial updates without having to write custom client script.

In this article, I have demonstrated the use of the UpdatePanelcontrol 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 ScriptManagercontrol in the Default.aspx file. Following is the markup code after adding the ScriptManagercontrol:

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

After the ScriptManagercontrol, we add an UpdatePanelcontrol as follows:

The UpdatePanelcontrol contains code for controls which must be partially updated. The code for the controls is written within the ContentTemplatechild element of the UpdatePanel. The UpdatePanelcontrol allows its content to be refreshed without causing a PostBackto 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:

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 ScriptManagercontrol as follows:

  • The EnableHistoryattribute is used to turn the history feature on or off.
  • The OnNavigateattribute specifies the event method for the Navigateevent of the ScriptManager.
  • The EnableSecureHistoryStateattribute 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:

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:

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 UpdateProgresscontrol is used to show a Progressmessage if a function takes a long time to run. The UpdateProgresscontrol is added to the markup code after the ScriptManagercontrol as follows:

The UpdateProgresscontrol 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:

System.Threading.Thread.sleep()
The modified function may look as follows:
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 UpdateProgresscontrol. 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)

Share

About the Author

Azim Zahir
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with NIIT (Mumbai, India) as a Senior Faculty. I enjoy programming as a hobby. My favorite technologies are Flash, Flex and Silverlight. Of late I have developed keen interest in WPF and Windows Mobile programming. Apart from computers, my favorite pastime is bicycling.

You may also be interested in...

Comments and Discussions

 
Question.. Pin
Member 1123623415-Nov-14 4:33
memberMember 1123623415-Nov-14 4:33 
AnswerRe: .. Pin
Azim Zahir17-Nov-14 16:27
memberAzim Zahir17-Nov-14 16:27 
Questionalright Pin
Member 1116074917-Oct-14 0:12
memberMember 1116074917-Oct-14 0:12 
AnswerRe: alright Pin
Azim Zahir18-Oct-14 19:03
memberAzim Zahir18-Oct-14 19:03 
QuestionGreat Pin
rasikasamith16-Mar-14 3:26
memberrasikasamith16-Mar-14 3:26 
AnswerRe: Great Pin
Azim Zahir24-Mar-14 17:23
memberAzim Zahir24-Mar-14 17:23 
QuestionIf i code on Page load Pin
narenderkumardhull13-May-12 23:00
membernarenderkumardhull13-May-12 23:00 
AnswerRe: If i code on Page load Pin
Azim Zahir15-May-12 17:02
memberAzim Zahir15-May-12 17:02 
QuestionBe wary of using ASP.NET AJAX Pin
DaveRRR14-Nov-11 7:51
memberDaveRRR14-Nov-11 7:51 
AnswerRe: Be wary of using ASP.NET AJAX Pin
Azim Zahir14-Nov-11 18:29
memberAzim Zahir14-Nov-11 18:29 
AnswerRe: Be wary of using ASP.NET AJAX Pin
RLCornish3-Dec-11 11:55
memberRLCornish3-Dec-11 11:55 
GeneralRe: Be wary of using ASP.NET AJAX Pin
DaveRRR4-Dec-11 6:34
memberDaveRRR4-Dec-11 6:34 
GeneralMy vote of 3 Pin
evenbetter12-Nov-11 23:28
memberevenbetter12-Nov-11 23: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
Web01 | 2.8.150804.3 | Last Updated 11 Nov 2011
Article Copyright 2011 by Azim Zahir
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid