Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Sunday, 26 April 2015

Google Charts with Jquery Ajax

If you are working for analytics project, you need a rich chart system to display big data results. Google is providing us a powerful chart tools that you can implement charts very simple, this tutorial will explain you how to implement Google charts with Jquery ajax JSON data. Try out there are many free interactive charts and data tools, take a quick look at this live demo.

Audio Recording with Custom Audio Player using Jquery and HTML5

Read more »
Share:

Monday, 16 February 2015

Facebook Style Background Image Upload and Position Adjustment.

I received many tutorial requests from my readers that asked to me how to design Facebook style ajax background image upload and position adjustment using Jquery. I have been published many tutorials about ajax image upload, this one is very interesting and it is a combination of many features. I has implemented this in Wall Script, this post will explain you how to design timeline HTML frame, CSS techniques and database design for background image system.

Facebook Style Background Image Upload and Position Adjustment.

Read more »
Share:

Tuesday, 8 July 2014

Ajax PHP Login Page with Shake Animation Effect.

I received few tutorial requests from my readers that asked to me how to create Ajax PHP login script, in this post I want to discuss how to create a simple Ajax PHP login with welcome page using MySQL database. This will explain you creating user tables, posting form values and storing and destroying the session values. If you are a PHP beginner take a quick look at this live demo with Username: 9lessons Password: 9lessons. This post has been updated with mysqli.

Ajax PHP Login Page

Read more »
Share:

Monday, 23 September 2013

Ajax Select and Upload Multiple Images with Jquery

Very few days back I had posted an article about Multiple ajax image upload without refreshing the page using jquery and PHP. In this post I have updated few lines of code that allows to user can select and upload multiple images in single shot, thanks to Lakshmi Maddukuri for sending me a useful piece of code. Just take a quick look this live demo.

Multiple Ajax Image Upload without Refreshing Page using Jquery and PHP.

Read more »
Share:

Monday, 5 August 2013

Multiple Ajax Image Upload without Refreshing Page using Jquery.

Today I am presenting the most important social networking feature called multiple ajax image upload without refreshing the page using jquery and PHP. We just modified few lines of code in jqery.form.js plugin and renamed that to jquery.wallform.js. This feature is one of the key feature in Wall Script sale, big thanks to Arun Sekar for this code trick.

Multiple Ajax Image Upload without Refreshing Page using Jquery and PHP.

Read more »
Share:

Saturday, 2 February 2013

Image Upload and Preview Control in ASP.NET Ajax

Image upload and previewing is a very basic requirement usually when we come across user registration page or add and edit an institution, etc. In this post I am providing here the sample which does the same using ASP.NET Ajax.

I had given here just a simple example just to upload and preview the image, I am not going to save the image in the Database or Load from the Database, but of course you can extend this control based on your requirements.

This is how the final screen will look once you complete the code:

image

You will need Ajax Control Toolkit for AsyncFileUpload control, this controls helps to perform the asynchronous operation without page refresh. Best way to get this through NuGet package manager in you project.

Now lets see the ASP.NET Page and the Code Behind for that.

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadImage.aspx.cs" Inherits="UploadImage" %>



   2:  



   3: <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>



   4:  



   5:  



   6: <!DOCTYPE html>



   7:  



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



   9: <head runat="server">



  10:     <title></title>



  11:  



  12:     <script language="javascript" type="text/javascript">
   1:  
   2:         function getRandomNumber() {
   3:             var randomnumber = Math.random(10000);
   4:             return randomnumber;
   5:         }
   6:  
   7:         function OnClientAsyncFileUploadComplete(sender, args) {
   8:             var handlerPage = '<%= Page.ResolveClientUrl("~/ImageRequestHandler.ashx")%>';
   9:             var queryString = '?randomno=' + getRandomNumber() + '&action=preview';
  10:             var src = handlerPage + queryString;
  11:             var clientId = '<%=previewImage.ClientID %>';
  12:         document.getElementById(clientId).setAttribute("src", src);
  13:     }
  14:     
</script>



  13:  



  14: </head>



  15: <body>



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



  17:         <ajaxToolkit:ToolkitScriptManager ID="toolKitScriptManager" runat="server">



  18:         </ajaxToolkit:ToolkitScriptManager>



  19:         <div>



  20:             <asp:Panel ID="pFileUpload" runat="server">



  21:                 <label>



  22:                     Image Source:</label>



  23:                 <ajaxToolkit:AsyncFileUpload ID="asyncFileUpload" runat="server" 



  24:                     OnClientUploadComplete="OnClientAsyncFileUploadComplete"



  25:                     OnUploadedComplete="OnAsyncFileUploadComplete" Width="374px" />



  26:                 <br />



  27:                 <asp:Image runat="server" ID="previewImage" Width="150px" BorderStyle="Double" BorderColor="Green" />



  28:             </asp:Panel>



  29:         </div>



  30:     </form>



  31: </body>



  32: </html>




The code above is very simple and self explanatory, still let me quickly give you a walkthrough. In the Script section of this page I am writing an function which gets called by the AsyncFileUpload control once the file upload to server is completed. Basically in Server side we are just saving the image temporarily in Session which is referenced in Handler section which I am going to cover very soon. In the same function we are calling the ImageHandler which gets the image from the session as mentioned above and write the image to response stream. Once the operation is over this function maps the source to the image control in the client side.



While calling the Image Handler sometimes in certain cases the browser caches the response stream due to which we may face the problem in refreshing the images. To overcome this you can see In the same script I have used a function to generate a random number which basically used to get the unique URL to call the ImageHandler and overcome the response caching issue.



I have almost explained the entire functionality still lets look into the ImagePreviewHandler and Code Behind part of the application.





   1: protected void OnAsyncFileUploadComplete(object sender, AsyncFileUploadEventArgs e)



   2: {



   3:     if (asyncFileUpload.FileBytes != null)



   4:     {



   5:         Context.Session.Add("SessionImage", asyncFileUpload.FileBytes);



   6:     }



   7: }








   1: <%@ WebHandler Language="C#" Class="ImageRequestHandler" %>



   2: using System;



   3: using System.Web;



   4:  



   5: public class ImageRequestHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState



   6: {



   7:     public void ProcessRequest(HttpContext context)



   8:     {



   9:         context.Response.Clear();



  10:  



  11:         if (context.Request.QueryString.Count != 0)



  12:         {



  13:             byte[] imageData = context.Session["SessionImage"] as byte[];



  14:  



  15:             if (imageData != null)



  16:             {



  17:                 context.Response.OutputStream.Write(imageData, 0, imageData.Length);



  18:                 context.Response.ContentType = "image/JPEG";



  19:             }



  20:         }



  21:     }



  22:  



  23:     public bool IsReusable {



  24:         get {



  25:             return false;



  26:         }



  27:     }



  28:  



  29: }






In the first snippet I have given the code behind of the ASP.NET page, which simple saves the image byte array into the Session in the  OnUploadedComplete  event of AsyncFileUpload control. This image byte array is used later in Image Handler to process further.



And finally in the second snippet I am showing the ASP.NET Generic Handler, in ProcessRequest I am fetching the image byte array from the Session and writing the image to the response of the page. A part from implementing IHttpHandler, I am also deriving the System.Web.SessionState.IRequiresSessionState, which provides me the ability to read and write to the session. This is very important in our case since we are using session variable to read the images in the Image Request Handler.



And that all we need. You can download the code from here.



Link: https://docs.google.com/file/d/0BzIjFd_Ps-MSaUhwdzl6NXRQMVE/edit?usp=sharing

Share:

Monday, 8 October 2012

RESTful Web Services JSON API Transformer with Java

This post is the continuation of my previous last post, I had explained how to create a basic RESTful web services API using Java, now I want to explain JSON transformer to work with input Get and Post methods parameters. Just added a new class called transformer it converts object data into JSON text output format.

RESTful Web Services with input parameters
Read more »
Share:

Monday, 29 September 2008

ASP.NET MVC Important Links

ASP.NET MVC Tutorials by ScottGu

Releases

The ASP.NET MVC Toolkit is currently provided as part of the ASP.NET 3.5 Extensions Preview: http://www.asp.net/downloads/3.5-extensions/

5 March 2008, at Mix08, CTP #2 was released:

The readme includes details of the extensive API changes and how to update existing (CTP #1) projects.

May 27, 2008: CTP3 is released

Applications

Advanced concepts / blog posts

The following is a list of blog posts on advanced topics.

Alternative view engines

Share:

Friday, 29 August 2008

Refreshing the Data in ObjectDataSource Dynamically

In my previous post, you have seen the paging example, but there is one small problem you may face, if you are using ControlParameter or QueryStringParameter, for instance take a scenario when you are using ASP.NET AJAX and you have GridView and Search button in update panel.

On page load, the ObjectDataSource will take the default parameters from the DropDownList and QueryString, but problems comes when we want to click Search Button to get the changed values of the DropDownList or the QueryString without posting the page again.

Generally to refresh the data of ObjectDataSource you often write

ObjectDataSource1.Select();

On Click of Search Button.

But hold on this is only good if you want to see the changed data from the database or Rebind the ObjectDataSource, but this will not pass the current value from the controls or query string as a parameter to the database Query or Procedure. Resulting in which you will keep getting the existing query result only, so here is the actual code below for which I have written such a big story.

GridView1.DataBind();

Yes just one line code, don't worry this internally calls the ObjectDataSource1.Select(), but will give you the desired result, I hope this will help you.

Thanks

~Brij
Share:

Sunday, 3 August 2008

Using ASP.NET 3.5 History Control with ASP.NET 2.0

Using Back Button in ASP.NET 2.0 and AJAX
This post will show you how to use ASP.NET 3.5 Ajax COntrolToolKit History control with ASP.NET 2.0,

As you might be aware of that microsoft has included AJAX with Framework 3.0, and from version 3.5 microsoft has also included History control in his AJAX Control toolkit,

Using history control we can use browser back button to navigate backwards in the pages containing AJAX Controls, which was normally not possible till Framework 2.0.

But if you are still using ASP.NET 2.0, then don't get disappointed you can use the same control in ASP.NET 2.0, remember to use this you don't need to install Framework 3.0, or 3.5.

You just need to do the steps given below:


1. Download the DLL, Microsoft.Web.Preview.dll, version 1.1.61025.0 or alrernatively download the source code from here and copy the DLL from bin folder.

2. From the Toolbox of you project, right click and Select Choose Items...

3. Locate the Microsoft.Web.Preview.dll and select OK.

4. You can find see the following tiems in the screenshot below, are added in your toolbox.

5. Now add the code below in your web.config
<
sectionGroup name="microsoft.web.preview"
type="Microsoft.Web.Preview.Configuration.PreviewSectionGroup, Microsoft.Web.Preview">
<
section name="search"
type="Microsoft.Web.Preview.Configuration.SearchSection, Microsoft.Web.Preview"
requirePermission="false" allowDefinition="MachineToApplication"/>
<
section name="searchSiteMap"
type="Microsoft.Web.Preview.Configuration.SearchSiteMapSection, Microsoft.Web.Preview"
requirePermission="false" allowDefinition="MachineToApplication"/>
<
section name="diagnostics"
type="Microsoft.Web.Preview.Configuration.DiagnosticsSection, Microsoft.Web.Preview"
requirePermission="false" allowDefinition="MachineToApplication"/>

</

sectionGroup>
6. Once you are done with this, open the webpage where you want to use the history control, and add the code below.

<

asp:History ID="History1" runat="server" OnNavigate="History1_Navigate">

</asp:History>

7. Open the codebehind and add the following piece of code

protected

void History1_Navigate(object sender, Microsoft.Web.Preview.UI.Controls.HistoryEventArgs args)

{

int startPage = 0;

if (args.State.ContainsKey("StartPage"))

{

startPage = (

int)args.State["StartPage"];

}

GridView1.PageIndex = startPage;

}

protected

void GridView1_PageIndexChanged(object sender, EventArgs e)

{

History1.AddHistoryPoint(

"StartPage", ((GridView)sender).PageIndex);

}

And thats it!!! You are ready to go...

This code uses GridView Paging, to demonstrate the HistoryControl

You can download the running sample from the here, C# Code, VB.NET Code

You can also refer my previous post

Using ASP.NET 3.5 Extensions History Control for complete Samples and Videos.

Sorry for the my code formatting, I tried to explain the steps, I hope this will help you.

Share:

Tuesday, 29 July 2008

Using ASP.NET 3.5 Extensions History Control

This post will provide useful links on how the ASP.NET Extensions Preview allows control over the Browser back button in Ajax. Normally this is not possible using AJAX Controls in WebBrowsers, because AJAX Control's partial postback is not added to the history of Web Browser.

Note : ASP.NET AJAX Extensions are available in the ASP.NET 3.5 Extensions Preview (December 2007).

Watch the video   |   Download the video   |   Get VB code  or  C# code

Important Links :

http://www.asp.net/AJAX/downloads/

http://weblogs.asp.net/davidbarkol/archive/2007/12/28/asp-net-3-5-extensions-history-control-tip.aspx

http://www.bestechvideos.com/2008/06/10/introduction-to-asp-net-ajax-history

http://www.asp.net/learn/ajax-videos/video-149.aspx
Share:

Using Back Button in ASP.NET 2.0 Ajax

One problem faced by a typical AJAX application is that a partial page update is not added to the history of the Web browser. This means that the browser’s Back button does not move back one AJAX step, but moves back one entire document, which is unlikely to be what the user expects. The below code could be written by a developer in response to a selection change within a list to to add the previous list selection to the browser's history via Nikhil's "HistoryControl":.

private void ContentList_SelectedIndexChanged(object sender,

EventArgs e)

{
   history.AddEntry(contentList.SelectedIndex.ToString();
}

 

private void HistoryControl_Navigate(object sender, HistoryEventArgs e)

{
int selectedIndex = 0;
    if (String.IsNullOrEmpty(e.Identifier) == false) {
        selectedIndex = Int32.Parse(e.Identifier);
}
// Update the content being displayed in the page
contentList.SelectedIndex = selectedIndex;
// Mark the update panels as needing an update
mainUpdatePanel.Update();

}

More...

Share:

Thursday, 24 April 2008

Ajax Error in Visual Studio 2008


Sometimes if we try to deploy an existing .NET ASP.NET 2.0 application which includes Ajax 1.0 library using Visual Studio 2005 we get following error


Could not load file or assembly ‘System.Web.Extensions, Version=3.5.0.0, ….


If you are using Ajax Famework Library, Visual Studio 2005 and Visual Studio 2008 installed in the same machine there are somethings you should be aware of.


Microsoft suggests that after the VS 2008 Beta 2 installation has finished, you should run this script to ensure that the installation of .NET Framework 3.5 Beta 2 will not affect the development of ASP.NET AJAX 1.0 applications.


If you want to target the AJAX 1.0 in Visual Studio 2008, check out this post Targeting AJAX 1.0 in VS 2008


Share:

Tuesday, 19 February 2008

HierarGrid - A hierarchical DataGrid that displays master-detail relations

 

Problem:

The ASP.NET DataGrid is a popular control to display data in a table form with editing, paging and sorting capabilites.
However it is only suitable to display single DataTables - there is no support for parent-child relations.

Goal:

To create a control that provides the standard DataGrid functionality and at the same time can display parent-child relations using templates to display the child elements.

Procedure:

Create a custom control called HierarGrid that derives from the DataGrid and a custom DataGridColumn called HierarColumn.

The HierarGrid takes a DataSet that contains relations between the tables.

While iterating over the parent table it checks the related tables for child rows and if one is found it dynamically loads a template for the child

row(s)

The template is rendered invisibly into the custom HierarColumn and when the user clicks the plus icon, the template content is copied via JavaScript into a newly created TableRow.

Download (V2.2):
How to get started:

By Denis Bauer
Share:

Monday, 18 February 2008

AJAX Basics

When I first posted my first Ajax links on this blog, some of my friends asked me to post more basics of Ajax, so that they can use the link more effectively, so today while surfing web I found very good topic on Ajax Basics originally posted on 4GuysfromRolla.com by Scott Mitchell. I hope this will help.

You can find the download links of Ajax components, samples and other utilities on my previous blog post

http://tutorials.indianjobs.co.in/2008/01/aspnet-ajax-useful-links.html

Introduction
Over the past several years web developers have started using JavaScript to make asynchronous postbacks to the web server that only transmit and receive the necessary data; these techniques are commonly referred to as AJAX. When properly implemented, AJAX-enabled web applications offer a highly interactive user interface whose responsiveness rivals that of desktop applications. Popular web applications like the social networking news site Digg and GMail are prime examples of AJAX techniques in action.

Since AJAX involves many disparate technologies at different layers in the networking stack, implementing AJAX without the use of an AJAX framework is difficult and error-prone. Fortunately, Microsoft has released a free AJAX framework for ASP.NET developers: Microsoft ASP.NET AJAX. This article is the first in a series of articles that examines the ASP.NET AJAX framework. This installment provides an overview of AJAX technologies and looks at getting started with Microsoft's framework. Future installments will focus on specific controls and scenarios. Read on to learn more!

A Brief History of Ajax
The client-server model is an architecture that involes two actors: a client and a server. The server passively waits for a request from a client and, upon receiving such a request, processes it and returns a reply. The client is responsible for initiating requests to the server, after which is waits for and then processes the data returned in the response. Web applications are classic examples of the client-server model. The client - a web browser, most often - sends a request to a web server for a particular resource. The resource may be static content like an HTML page or an image that the web server can simply return, or it may be dynamic content like an ASP.NET page that must first be processed on the web server before its generated markup can be sent back. Regardless, the interaction is the same: the client requests a particular resource, and the server returns it, be it the binary content of a JPG image or the HTML of a rendered ASP.NET page.

One drawback of the client-server models is latency. Clients must periodically communicate with the server to update the server with the user's input, or to retrieve the latest data from the server. During these periods, the user must wait while the request/response lifecycle plays out. This delay is most clearly evidenced in ASP.NET applications when a postback occurs. Imagine an eCommerce website that lists products in a grid whose contents can be sorted and paged through. However, stepping to the next page requires a postback to the server in order to retrieve the next page of products. Consequently, moving to the next page introduces a delay in the user experience that can take anywhere from less than a second to several seconds, depending on many factors (the user's Internet connection speed, the network congestion, the server load, the database query duration, and so on).

The main culprit here is that the postback requires that all of the page's form fields be sent back to the server and that the entire web page's content be returned to the browser. This volume of exchanged data is overkill since all that is really needed by the client is information about the next page of products. AJAX mitigates these latency issues by using JavaScript to make asynchronous postbacks to the web server; these postbacks transmit and receive the minimum amount of data necessary to perform the requested operation. For a more thorough background of AJAX, be sure to read Jesse James Garrett's essay where he coined the term "Ajax": Ajax: A New Approach to Web Applications.

There are a number of AJAX frameworks available. Most ASP.NET control vendors offer commercial AJAX implementations, and there are many open source libraries as well. In early 2006 Microsoft released its own AJAX framework, Microsoft ASP.NET AJAX, which is the focus of this article series.

An Overview of Microsoft ASP.NET AJAX
Microsoft's ASP.NET AJAX framework was designed to work with ASP.NET 2.0 and future versions; it does not work with ASP.NET version 1.x applications. The ASP.NET AJAX framework will ship with Visual Studio 2008 and ASP.NET version 3.5. ASP.NET 2.0 developers, however, need to download and install the framework from Microsoft's website; the "Getting Started with Microsoft ASP.NET AJAX" section later in this article includes a discussion on installing ASP.NET AJAX in a 2.0 environment.

The ASP.NET AJAX framework consists of client-side and server-side logic. There are a bevy of JavaScript libraries that simplify initiating an asychronous postback and processing the response from the server. The client-side libraries also include classes that mimic the .NET Framework's core classes and data types. The server-side components include ASP.NET controls that, when added to a page, implement various AJAX techniques. One such example is the ScriptManager control, which adds references to the client-side script in the page, so that the browser requesting the ASP.NET page downloads the appropriate JavaScript libraries as well. Consequently, you'll use the ScriptManager on any ASP.NET page where you want to utilize the ASP.NET AJAX framework.

In addition to the ScriptManager control, the ASP.NET AJAX framework includes a handful of other server-side controls, such as the UpdatePanel, the Timer, and the UpdateProgress controls. The UpdatePanel control allows you to define a portion of the page that will be updated by an asynchronous request. In short, it allows you to make partial postbacks rather than a full page postback. This improves the responsiveness of the page in two ways: first, when a partial postback occurs only the data relevant to that UpdatePanel is sent to the server, and only the corresponding data is returned; and, second, the partial page postback does not cause the entire page to be "re-drawn" by the browser, so there's no "flash" that is all too common when making full postbacks.

The UpdatePanel is one of the core pieces of the ASP.NET AJAX framework, and one which we will be examining later on in this article. Once an UpdatePanel has been added to a page, you can add the standard ASP.NET web controls - TextBoxes, Buttons, GridViews, DropDownLists, and so on - and they will automatically take advantage of AJAX techniques. For example, if you have a Button and a TextBox in an UpatePanel and the Button is clicked, a partial postback will occur. The Button's Click event handler will be called on the server-side, as expected, and the value of the TextBox's Text property can be accessed as usual. Moreover, any other Web controls within the same UpdatePanel can have their properties read or assigned and they will be re-rendered and their output updated in the user's browser.

In addition to the base server-side controls (the ScriptManager, UpdatePanel, Timer, and so on), Microsoft offers an additional set of interactive controls via the AJAX Control Toolkit. This toolkit includes ratings controls, sliders, modal popup windows, and so forth.

Getting Started with Microsoft ASP.NET AJAX
For ASP.NET 2.0 developers, the first step in working with Microsoft ASP.NET AJAX is to download the AJAX Extensions and, optionally, the AJAX Control Toolkit. (ASP.NET 3.5 developers will already have the ASP.NET AJAX framework installed.)

Note: This article only looks at working with the AJAX Extensions (the core of the framework) and leaves the Control Toolkit for a future installment.

To download the ASP.NET AJAX 1.0 framework, visit this page and click the Download button. The ASP.NET AJAX framework is packaged up as an MSI file. Once you've downloaded the MSI file to your computer, double-click it to install the framework. After downloading and installing the ASP.NET AJAX framework, start Visual Studio and choose to create a New Project. In the New Project dialog box you should see a new project type named "ASP.NET AJAX-Enabled Web Application."

Visual Studio includes a new Project Type named ASP.NET AJAX-Enabled Web Application.

Creating an ASP.NET AJAX-Enabled Web Application creates a new Web Application Project with the System.Web.Extensions assembly added as a reference. The System.Web.Extensions assembly contains the core client- and server-side pieces of Microsoft's ASP.NET AJAX framework. Also, the Toolbox includes an AJAX Extensions category with the core server-side AJAX controls.

Our First ASP.NET AJAX Example: Using the UpdatePanel


The UpdatePanel is useful in situations where you only want a portion of the page to postback rather than the entire page. Such a limited postback is called a partial postback, and is easy to implement using the UpdatePanel. As you know, many ASP.NET controls can cause postbacks: Button controls, when clicked; DropDownLists and CheckBoxes, when their AutoPostBack property is set to True; and so on. Under normal circumstances, when these controls cause a postback, the entire page is posted back. All form field values are sent from the browser to the server. The server then re-renders the entire page and returns the complete HTML, which is then redisplayed by the browser.

When these controls appear in an UpdatePanel, however, a partial page postback is initiated instead. Only the form fields in the UpdatePanel are sent to the server. The server then re-renders the page, but only sends back the markup for those controls in the UpdatePanel. The client-side script that initiated the partial postback receives the partial markup results from the server and seamlessly updates the display in the browser with the returned values. Consequently, the UpdatePanel improves the reponsiveness of a page by reducing the amount of data exchanged between the client and the server and by "redrawing" only the portion of the screen that kicked off the partial page postback.

Let's take a look at the UpdatePanel in action. The following demo, which is downloadable at the end of this article, shows a simple example. The UpdatePanel in the demo includes only two controls: a Label and a Button. The Label Web control displays the text of a randomly selected joke. Clicking the Button loads a new randomly selected joke into the Label. If you are following along at your computer, start by adding a new ASP.NET page to the ASP.NET AJAX-Enabled Web Application we created back in the "Getting Started with Microsoft ASP.NET AJAX" section.

Whenever we use the ASP.NET AJAX framework in a page, we need to start by adding a ScriptManager control, so start by adding a ScriptManager to the page. Next, add an UpdatePanel to the page. Within that UpdatePanel, add a Label control and a Button control. After performing these steps, the declarative markup in your web page should look similar to the following:

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

<asp:UpdatePanel ID="JokeUpdatePanel" runat="server">
<ContentTemplate>
<asp:Label ID="JokeText" runat="server" Font-Italic="False" Font-Names="Comic Sans MS"
Font-Size="Large"></asp:Label>
<br />
<br />
<asp:Button ID="NewJokeButton" runat="server" Text="Show Me a Random Joke!" />
</ContentTemplate>
</asp:UpdatePanel>

At this point, all that remains is to write the server-side code. When the page is first loaded we want to set the JokeText Label's Text property to a randomly selected joke; likewise, whenever the NewJokeButton is clicked, we want to refresh the Label's Text property with a new joke.

protected void Page_Load(object sender, EventArgs e)
{
JokeText.Text = GetRandomJoke();
}

protected void NewJokeButton_Click(object sender, EventArgs e)
{
JokeText.Text = GetRandomJoke();
}

private string GetRandomJoke()
{
// Get a random number
Random r = new Random();
switch (r.Next(5))
{
case 0:
return "Why did the chicken cross the road? To get to the other side!!";
case 1:
return "How much do pirates pay for their earrings? A Buccaneer!";
case 2:
return "Why did the computer squeak? Because someone stepped on it's mouse!";
case 3:
return "What is a golfer's favorite letter? Tee!";
default:
return "A child comes home from his first day at school. Mom asks, "What did you learn today?" "Not enough," the kid replies, "I have to go back tomorrow."";
}
}

At this point we have a page that will utilize AJAX techniques to make a partial page postback when the Button in the UpdatePanel is clicked. Consequently, clicking the "Show Me a Random Joke!" button displays a new joke promptly without having the entire page refresh. Granted, this is an overly simple example since the page already is very lightweight, but this concept can be extended to more real-world scenarios (and will be, in future installments of this article series). For example, you might have a page that has several grids on it showing a plethora of data. You could place each grid in its own UpdatePanel. That way, when a user sorted or paged a grid, a partial postback would occur and the particular grid could be paged or sorted without requiring a full postback.

The takeaway here is that implementing AJAX techniques in an ASP.NET application using the ASP.NET AJAX framework is remarkably easy. The ScriptManager and UpdatePanel controls automatically handle all of the complexities involved with initiating the asynchronous postback and displaying the returned data.

Looking Forward...
This article only looked at a simple UpdatePanel example. In real-world scenarios, however, things aren't always as simple. For example, we might want to have some event external to the UpdatePanel trigger a partial postback. We've not yet looked at working directly with the client-side AJAX libraries; nor have we explored the wealth of controls in the AJAX Control Toolkit. These, and many more topics, You can find the download links of Ajax components, samples and other utilities on my previous blog post
http://tutorials.indianjobs.co.in/2008/01/aspnet-ajax-useful-links.html

Happy Programming!

By Scott Mitchell

Share: